Files
MediaCollectorLibary/app/Controllers/AuthController.php
Lars Behrends 929ee43001 first commit
2025-10-17 13:29:28 +02:00

77 lines
2.4 KiB
PHP

<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Services\AuthService;
use Slim\Views\Twig;
class AuthController extends Controller
{
private AuthService $auth;
public function __construct(AuthService $auth, Twig $view)
{
parent::__construct($view);
$this->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');
}
}