auth = $auth; } public function showLogin(Request $request, Response $response, $args) { // If already logged in, redirect to dashboard if ($this->auth->isLoggedIn()) { return $response->withStatus(302)->withHeader('Location', '/'); } return $this->view->render($response, 'auth/login.twig', [ 'title' => 'Login', 'csrf_token' => $this->auth->generateCSRFToken() ]); } public function login(Request $request, Response $response, $args) { $data = $request->getParsedBody(); $username = $data['username'] ?? ''; $password = $data['password'] ?? ''; $csrfToken = $data['csrf_token'] ?? ''; // Verify CSRF token if (!$this->auth->verifyCSRFToken($csrfToken)) { return $this->view->render($response->withStatus(400), 'auth/login.twig', [ 'title' => 'Login', 'error' => 'Invalid CSRF token', 'csrf_token' => $this->auth->generateCSRFToken() ]); } // Validate input if (empty($username) || empty($password)) { return $this->view->render($response->withStatus(400), 'auth/login.twig', [ 'title' => 'Login', 'error' => 'Username and password are required', 'csrf_token' => $this->auth->generateCSRFToken() ]); } // Attempt login if ($this->auth->login($username, $password, $_SERVER['REMOTE_ADDR'] ?? null)) { return $response->withStatus(302)->withHeader('Location', '/'); } // Login failed return $this->view->render($response->withStatus(401), 'auth/login.twig', [ 'title' => 'Login', 'error' => 'Invalid username or password', 'csrf_token' => $this->auth->generateCSRFToken() ]); } public function logout(Request $request, Response $response, $args) { $this->auth->logout(); return $response->withStatus(302)->withHeader('Location', '/login'); } }