Files
novaconium/controllers/authenticate.php
T
2026-07-04 07:43:33 -07:00

71 lines
2.4 KiB
PHP

<?php
use Nickyeoman\Validation;
$v = new Nickyeoman\Validation\Validate();
$url_success = '/novaconium/dashboard';
$url_fail = '/novaconium/login';
// Don't go further if already logged in
if ( !empty($ctx->session->get('username')) ) {
$ctx->redirect->url($url_success);
makeitso();
}
// Make sure Session Token is correct
if ($ctx->session->get('token') != $ctx->post->get('token')) {
$ctx->messages->addMessage('error', "Invalid Session.");
$ctx->log->error("Login Authentication - Invalid Session Token");
}
// Handle Username
$rawUsername = $ctx->post->get('username', null);
$cleanUsername = $v->clean($rawUsername); // Clean the input
$username = strtolower($cleanUsername); // Convert to lowercase
if (!$username) {
$ctx->messages->addMessage('error', "No Username given.");
}
// Handle Password
$password = $v->clean($ctx->post->get('password', null));
if ( empty($password) ) {
$ctx->messages->addMessage('error', "Password Empty.");
}
/*************************************************************************************************************
* Query Database
************************************************************************************************************/
if ($ctx->messages->count('error') === 0) {
$query = "SELECT id, username, email, password, blocked FROM users WHERE username = ? OR email = ?";
$matched = $ctx->db->getRow($query, [$username, $username]);
if (empty($matched)) {
$ctx->messages->addMessage('error', "User or Password incorrect.");
$ctx->log->warning("Login Authentication - Login Error, user doesn't exist");
}
}
if ($ctx->messages->count('error') === 0) {
// Re-apply pepper
$peppered = hash_hmac('sha3-512', $password, $ctx->config['secure_key']);
// Verify hashed password
if (!password_verify($peppered, $matched['password'])) {
$ctx->messages->addMessage('error', "User or Password incorrect.");
$ctx->log->warning("Login Authentication - Login Error, password wrong");
}
}
// Process Login or Redirect
if ($ctx->messages->count('error') === 0) {
$query = "SELECT groupName FROM user_groups WHERE user_id = ?";
$groups = $ctx->db->getRow($query, [$matched['id']]);
$ctx->session->set('username', $cleanUsername);
$ctx->session->set('group', $groups['groupName']);
$ctx->redirect->url($url_success);
$ctx->log->info("Login Authentication - Login Success");
} else {
$ctx->redirect->url($url_fail);
}