76 lines
2.2 KiB
PHP
76 lines
2.2 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 SetupController
|
|
{
|
|
private AuthService $authService;
|
|
|
|
public function __construct(AuthService $authService)
|
|
{
|
|
$this->authService = $authService;
|
|
}
|
|
|
|
public function form(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
|
{
|
|
if ($this->authService->getUserCount() > 0) {
|
|
return $response
|
|
->withHeader('Location', '/login')
|
|
->withStatus(302);
|
|
}
|
|
|
|
ob_start();
|
|
$error = null;
|
|
require dirname(__DIR__, 2) . '/templates/auth/setup.php';
|
|
$body = ob_get_clean();
|
|
$response->getBody()->write($body);
|
|
return $response;
|
|
}
|
|
|
|
public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
|
{
|
|
if ($this->authService->getUserCount() > 0) {
|
|
return $response
|
|
->withHeader('Location', '/login')
|
|
->withStatus(302);
|
|
}
|
|
|
|
$data = $request->getParsedBody();
|
|
$username = trim($data['username'] ?? '');
|
|
$password = $data['password'] ?? '';
|
|
|
|
if (strlen($username) < 2 || strlen($password) < 8) {
|
|
ob_start();
|
|
$error = 'Username must be at least 2 chars, password at least 8';
|
|
require dirname(__DIR__, 2) . '/templates/auth/setup.php';
|
|
$body = ob_get_clean();
|
|
$response->getBody()->write($body);
|
|
return $response->withStatus(400);
|
|
}
|
|
|
|
try {
|
|
$user = $this->authService->createUser($username, $password);
|
|
} catch (\RuntimeException $e) {
|
|
ob_start();
|
|
$error = $e->getMessage();
|
|
require dirname(__DIR__, 2) . '/templates/auth/setup.php';
|
|
$body = ob_get_clean();
|
|
$response->getBody()->write($body);
|
|
return $response->withStatus(400);
|
|
}
|
|
|
|
$_SESSION['user_id'] = $user->id;
|
|
$_SESSION['username'] = $user->username;
|
|
|
|
return $response
|
|
->withHeader('Location', '/dashboard')
|
|
->withStatus(302);
|
|
}
|
|
}
|