'Login', 'page_content' => function() { View::render('@auth/login', []); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_show_login_form']); http_response_code(500); echo 'Erro interno do servidor'; } } /** * Handle the login request. */ public function handleLogin(): void { try { // Validação simples e sanitização $email = Sanitize::email($_POST['email'] ?? ''); $password = $_POST['password'] ?? ''; $rememberMe = isset($_POST['remember_me']); // Validar campos obrigatórios if (empty($email) || empty($password)) { $this->errorResponse('Email and password are required', 400); return; } // Validar formato de email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->errorResponse('Invalid email format', 400); return; } // Tentar login if (Auth::login($email, $password, $rememberMe)) { // Redirecionar após login bem-sucedido $this->successResponse([], 'Login successful'); } else { $this->errorResponse('Invalid credentials', 401); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_handle_login']); $this->errorResponse('Internal server error', 500); } } /** * Handle the logout request. */ public function logout(): void { try { Auth::logout(); header('Location: /login'); exit(); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_logout']); header('Location: /login?error=logout_error'); exit(); } } public function loginBasic(): void { try { View::render('layouts/auth.php', [ 'title' => 'Sign In', 'page_content' => function() { View::render('@auth/login'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_login_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } public function registerBasic(): void { try { View::render('layouts/auth.php', [ 'title' => 'Create Account', 'page_content' => function() { View::render('@auth/signup/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_register_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } public function passResetBasic(): void { try { View::render('layouts/auth.php', [ 'title' => 'Password Reset', 'page_content' => function() { View::render('@auth/pass/reset/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_pass_reset_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } public function loginCover(): void { try { View::render('layouts/auth.php', [ 'title' => 'Sign In', 'page_content' => function() { View::render('@auth/signin/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_login_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public function registerCover(): void { try { View::render('layouts/auth.php', [ 'title' => 'Create Account', 'page_content' => function() { View::render('@auth/signup/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_register_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public function passResetCover(): void { try { View::render('layouts/auth.php', [ 'title' => 'Password Reset', 'page_content' => function() { View::render('@auth/pass/reset/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_pass_reset_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public function lockScreen(): void { try { View::render('layouts/auth.php', [ 'title' => 'Lock Screen', 'page_content' => function() { View::render('@auth/lockscreen/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_lock_screen']); http_response_code(500); echo 'Erro interno do servidor'; } } public function unlock(): void { try { // Check if request is AJAX if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid request']); return; } // Check if user is logged in (has session) if (!isset($_SESSION['user_id'])) { echo json_encode(['success' => false, 'message' => 'No active session found. Please login again.', 'redirect' => '/login']); return; } // Get password from POST $password = $_POST['password'] ?? ''; if (empty($password)) { echo json_encode(['success' => false, 'message' => 'Password is required']); return; } // Get user from database $db = DatabaseManager::getInstance(); $stmt = $db->prepare("SELECT id, password FROM users WHERE id = ? AND is_active = 1"); $stmt->execute([$_SESSION['user_id']]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) { echo json_encode(['success' => false, 'message' => 'User not found']); return; } // Verify password if (password_verify($password, $user['password'])) { // Password is correct, redirect to dashboard echo json_encode(['success' => true, 'message' => 'Unlocked successfully']); } else { echo json_encode(['success' => false, 'message' => 'Invalid password']); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_unlock']); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Internal server error']); } } public function twoStepVerification(): void { try { View::render('layouts/auth.php', [ 'title' => 'Two Step Verification', 'page_content' => function() { View::render('@auth/twostep/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_two_step_verification']); http_response_code(500); echo 'Erro interno do servidor'; } } public function errors404(): void { try { View::render('layouts/auth.php', [ 'title' => '404 Error', 'page_content' => function() { View::render('@auth/404/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_errors_404']); http_response_code(500); echo 'Erro interno do servidor'; } } public function errors404Cover(): void { try { View::render('layouts/auth.php', [ 'title' => '404 Error', 'page_content' => function() { View::render('@auth/404/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_errors_404_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public function errors404Alt(): void { try { View::render('layouts/main.php', [ 'title' => '404 Error', 'page_content' => function() { View::render('@auth/404/alt'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_errors_404_alt']); http_response_code(500); echo 'Erro interno do servidor'; } } public function errors500(): void { try { View::render('layouts/main.php', [ 'title' => '500 Error', 'page_content' => function() { View::render('@auth/500'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_errors_500']); http_response_code(500); echo 'Erro interno do servidor'; } } public function errorsOffline(): void { try { View::render('layouts/main.php', [ 'title' => 'Offline', 'page_content' => function() { View::render('@auth/offline'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_errors_offline']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authSuccessMsgCoverPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Success Message', 'page_content' => function() { View::render('@auth/success/msg/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_success_msg_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authSuccessMsgBasicPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Success Message', 'page_content' => function() { View::render('@auth/success/msg/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_success_msg_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authPassChangeCoverPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Password Change', 'page_content' => function() { View::render('@auth/pass/change/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_pass_change_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authPassChangeBasicPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Password Change', 'page_content' => function() { View::render('@auth/pass/change/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_pass_change_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authTwostepCoverPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Two Step Verification', 'page_content' => function() { View::render('@auth/twostep/cover'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_twostep_cover']); http_response_code(500); echo 'Erro interno do servidor'; } } public static function authTwostepBasicPage(): void { try { View::render('layouts/auth.php', [ 'title' => 'Two Step Verification', 'page_content' => function() { View::render('@auth/twostep/basic'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_twostep_basic']); http_response_code(500); echo 'Erro interno do servidor'; } } // API Methods - SEGURANÇA MÁXIMA APLICADA public static function loginApi(): void { try { // Validar método HTTP if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Método não permitido']); return; } // Sanitizar inputs $email = Sanitize::email($_POST['email'] ?? ''); $password = $_POST['password'] ?? ''; // Validar campos obrigatórios if (empty($email) || empty($password)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Email e password são obrigatórios']); return; } // Validar formato de email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Formato de email inválido']); return; } // Tentar login if (Auth::login($email, $password, false)) { header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => 'Login realizado com sucesso']); } else { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Credenciais inválidas']); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_login_api']); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']); } } public static function logoutApi(): void { try { // Validar método HTTP if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Método não permitido']); return; } Auth::logout(); header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => 'Logout realizado com sucesso']); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_logout_api']); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']); } } public static function registerApi(): void { try { // Validar método HTTP if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Método não permitido']); return; } // Sanitizar inputs $email = Sanitize::email($_POST['email'] ?? ''); $password = $_POST['password'] ?? ''; $confirmPassword = $_POST['confirm_password'] ?? ''; $firstName = Sanitize::string($_POST['first_name'] ?? ''); $lastName = Sanitize::string($_POST['last_name'] ?? ''); // Validar campos obrigatórios if (empty($email) || empty($password) || empty($confirmPassword) || empty($firstName) || empty($lastName)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Todos os campos são obrigatórios']); return; } // Validar formato de email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Formato de email inválido']); return; } // Validar passwords if ($password !== $confirmPassword) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Passwords não coincidem']); return; } if (strlen($password) < 8) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Password deve ter pelo menos 8 caracteres']); return; } // Verificar se email já existe $userModel = new \App\Modules\Users\Models\UserModel(); if ($userModel->findByEmail($email)) { http_response_code(409); echo json_encode(['success' => false, 'message' => 'Email já registado']); return; } // Criar utilizador $userId = $userModel->create([ 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'password' => password_hash($password, PASSWORD_DEFAULT), 'is_active' => 1 ]); if ($userId) { http_response_code(201); echo json_encode(['success' => true, 'message' => 'Registo realizado com sucesso']); } else { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Erro ao criar utilizador']); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_register_api']); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']); } } public static function userApi(): void { try { // Validar método HTTP if ($_SERVER['REQUEST_METHOD'] !== 'GET') { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Método não permitido']); return; } // Verificar autenticação if (!Auth::check()) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']); return; } // Obter dados do utilizador autenticado $userId = Auth::id(); if (!$userId) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']); return; } $userModel = new \App\Modules\Users\Models\UserModel(); $userData = $userModel->find($userId); if (!$userData) { http_response_code(404); echo json_encode(['success' => false, 'message' => 'Utilizador não encontrado']); return; } unset($userData['password'], $userData['remember_token'], $userData['remember_token_expires']); header('Content-Type: application/json'); echo json_encode(['success' => true, 'data' => $userData]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'auth_user_api']); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']); } } }