ref: master
app/controllers/AuthController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?php require_once __DIR__ . '/../services/AuthService.php'; class AuthController { private $authService; public function __construct() { $this->authService = new AuthService(); } public function login() { $email = $_POST['email']; $password = $_POST['password']; $sanitizedPassword = htmlspecialchars($password); $user = $this->authService->login($email, $sanitizedPassword); if ($user) { $_SESSION['user_id'] = $user->getId(); $_SESSION['user_email'] = $user->getEmail(); header('Location: /dashboard'); exit(); } else { // TODO: Flash messages echo 'Usuário ou senha inválidos'; } } public function register() { $email = $_POST['email']; $userName = $_POST['username']; $password = $_POST['password']; $passwdConfirmation = $_POST['password_confirmation']; if ($password != $passwdConfirmation) { // TODO: Flash messages echo 'As senhas não conferem'; return; } if (empty($email) || empty($password) || empty($userName)) { throw new Exception("Email, username or password cannot be empty."); } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new Exception("Invalid email format."); } $cryptographicPassword = password_hash($password, PASSWORD_DEFAULT); $user = $this->authService->register($userName, $email, $cryptographicPassword); if ($user) { header('Location: /login'); exit(); } else { // TODO: Flash messages echo 'Erro ao cadastrar usuário'; } } public function logout() { $_SESSION = []; session_destroy(); if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie( session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); } header('Location: /'); exit(); } } |