68 lines
1.9 KiB
PHP
68 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domovoy\Controllers;
|
|
|
|
use Domovoy\Services\AuthService;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
|
|
class AuthController
|
|
{
|
|
private AuthService $authService;
|
|
|
|
public function __construct(AuthService $authService)
|
|
{
|
|
$this->authService = $authService;
|
|
}
|
|
|
|
public function loginForm(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
|
{
|
|
if (isset($_SESSION['user_id'])) {
|
|
return $response
|
|
->withHeader('Location', '/dashboard')
|
|
->withStatus(302);
|
|
}
|
|
|
|
ob_start();
|
|
require dirname(__DIR__, 2) . '/templates/auth/login.php';
|
|
$body = ob_get_clean();
|
|
$response->getBody()->write($body);
|
|
return $response;
|
|
}
|
|
|
|
public function login(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
|
{
|
|
$data = $request->getParsedBody();
|
|
$username = $data['username'] ?? '';
|
|
$password = $data['password'] ?? '';
|
|
|
|
$user = $this->authService->authenticate($username, $password);
|
|
|
|
if ($user === null) {
|
|
ob_start();
|
|
$error = 'Invalid username or password';
|
|
require dirname(__DIR__, 2) . '/templates/auth/login.php';
|
|
$body = ob_get_clean();
|
|
$response->getBody()->write($body);
|
|
return $response->withStatus(401);
|
|
}
|
|
|
|
$_SESSION['user_id'] = $user->id;
|
|
$_SESSION['username'] = $user->username;
|
|
|
|
return $response
|
|
->withHeader('Location', '/dashboard')
|
|
->withStatus(302);
|
|
}
|
|
|
|
public function logout(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
|
{
|
|
session_destroy();
|
|
return $response
|
|
->withHeader('Location', '/login')
|
|
->withStatus(302);
|
|
}
|
|
}
|