i finally committed i guess

Signed-off-by: boris <boris@borishub.co.uk>
This commit is contained in:
boris
2025-03-15 01:59:16 +00:00
parent 8de2b7f29e
commit 709596eea2
113 changed files with 25075 additions and 54344 deletions

194
logincontroller.php Normal file → Executable file
View File

@@ -1,52 +1,158 @@
<?php
require_once("Models/User.php");
require_once("Models/AuthService.php");
// create user and dataset object
$user = new User();
$userDataSet = new UserDataSet();
// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if (isset($_POST["loginButton"])) {
$username = $_POST["username"];
// hash password
$password = (hash("sha256", $_POST["password"]));
// if login error, show captcha
if (isset($view->loginError)) {
$generatedCaptcha = $_POST["generatedCaptcha"];
$userCaptcha = $_POST["captcha"];
// if captcha wrong, say so
if ($generatedCaptcha !== $userCaptcha) {
$view->loginError = "Incorrect CAPTCHA.";
return;
}
}
// create a new student dataset object that we can generate data from
// Error handling is VERY hacky, because of the lack of JS usage.
if($userDataSet->checkUserCredentials($username, $password)) {
$user->Authenticate($username, $password);
// Unset modal boolean to hide it's usage.
unset($_GET['modal']);
} else {
// Add error message and redirect to display modal
$view->loginError = "Invalid username or password.";
// Set modal boolean to header to allow modal to reappear
$queryParams = http_build_query(['modal' => 'true']);
header("Location: {$_SERVER['PHP_SELF']}?$queryParams");
// Handle OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
// Create service objects
$authService = new AuthService();
// Start session for CAPTCHA handling only
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
header('Content-Type: application/json');
if (isset($_POST["action"])) {
switch ($_POST["action"]) {
case "login":
$username = $_POST["username"];
$password = hash("sha256", $_POST["password"]);
// Check if CAPTCHA is required (after 3 failed attempts)
$loginAttempts = isset($_SESSION['loginAttempts']) ? $_SESSION['loginAttempts'] : 0;
if ($loginAttempts >= 3) {
// Validate CAPTCHA
if (!isset($_POST["captchaInput"]) || !isset($_SESSION['captcha']) ||
$_POST["captchaInput"] !== $_SESSION['captcha']) {
// Generate new CAPTCHA for next attempt
$captcha = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 5);
$_SESSION['captcha'] = $captcha;
echo json_encode([
"error" => "Incorrect CAPTCHA.",
"captcha" => $captcha
]);
exit;
}
// Clear CAPTCHA after successful validation
unset($_SESSION['captcha']);
}
// Authenticate user
$user = new User();
$token = $user->Authenticate($username, $password);
if ($token) {
// Reset login attempts on successful login
$_SESSION['loginAttempts'] = 0;
// Generate refresh token
$refreshToken = $authService->generateRefreshToken([
'id' => $user->getUserId(),
'username' => $user->getUsername(),
'accessLevel' => $user->getAccessLevel()
]);
echo json_encode([
'success' => true,
'token' => $token,
'refreshToken' => $refreshToken,
'user' => [
'id' => $user->getUserId(),
'username' => $user->getUsername(),
'accessLevel' => $user->getAccessLevel()
],
'redirect' => '/'
]);
} else {
// Increment login attempts
$_SESSION['loginAttempts'] = $loginAttempts + 1;
// If this failure triggers CAPTCHA, generate it
if ($_SESSION['loginAttempts'] >= 3) {
$captcha = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 5);
$_SESSION['captcha'] = $captcha;
echo json_encode([
"error" => "Invalid username or password.",
"captcha" => $captcha
]);
} else {
echo json_encode(["error" => "Invalid username or password."]);
}
}
break;
case "logout":
// Clear session (only used for CAPTCHA)
session_unset();
session_destroy();
echo json_encode([
"success" => true,
"redirect" => '/'
]);
break;
case "refresh":
// Validate refresh token
if (!isset($_POST['refreshToken'])) {
echo json_encode([
"valid" => false,
"error" => "No refresh token provided"
]);
exit;
}
$refreshToken = $_POST['refreshToken'];
$newToken = $authService->refreshToken($refreshToken);
if ($newToken) {
echo json_encode([
"valid" => true,
"token" => $newToken
]);
} else {
echo json_encode([
"valid" => false,
"error" => "Invalid or expired refresh token"
]);
}
break;
case "validate":
// Validate JWT token using the simplified approach
$auth = User::checkAuth(false);
if ($auth) {
echo json_encode([
"valid" => true,
"user" => [
"id" => $auth['uid'],
"username" => $auth['username'],
"accessLevel" => $auth['accessLevel']
]
]);
} else {
echo json_encode([
"valid" => false
]);
}
break;
}
exit;
}
}
if(isset($_POST['closeButton'])) {
unset($_GET['modal']);
}
if (isset($_POST["logoutButton"]))
{
$user->logout();
}
// for login errors; show login modal until captcha solved
if (isset($_GET['modal']) && $_GET['modal'] === 'true') {
$view->loginError = $view->loginError ?? "Please solve the Captcha and try again.";
}