Итерация 1: каркас Slim 4 приложения

- Slim 4 + php-di контейнер с маршрутизацией
- Docker Compose: app (PHP 8.3-FPM) + web (nginx) + db (MariaDB)
- Phinx миграция: таблица users (uuid, username, password_hash)
- Auth: login/logout с сессиями
- Setup: создание первого пользователя
- Dashboard с layout (Bootstrap 5.3)
- CLI: bin/console, bin/run-scan-worker.php
- Smoke test: scripts/check.sh
- README.md, PLAN.md
This commit is contained in:
2026-05-26 07:26:55 +08:00
commit e7732f5cee
31 changed files with 8790 additions and 0 deletions
+67
View File
@@ -0,0 +1,67 @@
<?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);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Domovoy\Controllers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class DashboardController
{
public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
ob_start();
$username = $_SESSION['username'] ?? 'User';
require dirname(__DIR__, 2) . '/templates/dashboard/index.php';
$body = ob_get_clean();
$response->getBody()->write($body);
return $response;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?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);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Domovoy\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Routing\RouteContext;
class AuthMiddleware
{
public function __invoke(
ServerRequestInterface $request,
\Psr\Http\Server\RequestHandlerInterface $handler
): ResponseInterface {
$path = $request->getUri()->getPath();
$publicPaths = ['/login', '/setup'];
$isPublic = in_array($path, $publicPaths, true);
if (!isset($_SESSION['user_id']) && !$isPublic) {
$response = new \Slim\Psr7\Response();
return $response
->withHeader('Location', '/login')
->withStatus(302);
}
// If logged in and trying to access login/setup, redirect to dashboard
if (isset($_SESSION['user_id']) && $isPublic) {
$response = new \Slim\Psr7\Response();
return $response
->withHeader('Location', '/dashboard')
->withStatus(302);
}
return $handler->handle($request);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Domovoy\Models;
class User
{
public ?string $id = null;
public string $username = '';
public string $passwordHash = '';
public ?\DateTimeImmutable $createdAt = null;
public ?\DateTimeImmutable $updatedAt = null;
public static function fromArray(array $data): self
{
$user = new self();
$user->id = $data['id'];
$user->username = $data['username'];
$user->passwordHash = $data['password_hash'];
$user->createdAt = new \DateTimeImmutable($data['created_at']);
$user->updatedAt = new \DateTimeImmutable($data['updated_at']);
return $user;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use PDO;
use Domovoy\Models\User;
class UserRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function findById(string $id): ?User
{
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? User::fromArray($row) : null;
}
public function findByUsername(string $username): ?User
{
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);
$row = $stmt->fetch();
return $row ? User::fromArray($row) : null;
}
public function findAll(): array
{
$stmt = $this->pdo->query('SELECT * FROM users ORDER BY created_at DESC');
$users = [];
while ($row = $stmt->fetch()) {
$users[] = User::fromArray($row);
}
return $users;
}
public function count(): int
{
$stmt = $this->pdo->query('SELECT COUNT(*) FROM users');
return (int) $stmt->fetchColumn();
}
public function save(User $user): void
{
if ($user->id === null) {
$user->id = \Ramsey\Uuid\Uuid::uuid4()->toString();
}
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
$user->updatedAt = new \DateTimeImmutable($now);
if ($user->createdAt === null) {
$user->createdAt = new \DateTimeImmutable($now);
}
$stmt = $this->pdo->prepare(
'INSERT INTO users (id, username, password_hash, created_at, updated_at)
VALUES (:id, :username, :password_hash, :created_at, :updated_at)'
);
$stmt->execute([
'id' => $user->id,
'username' => $user->username,
'password_hash' => $user->passwordHash,
'created_at' => $user->createdAt->format('Y-m-d H:i:s'),
'updated_at' => $user->updatedAt->format('Y-m-d H:i:s'),
]);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services;
use Domovoy\Models\User;
use Domovoy\Repositories\UserRepository;
class AuthService
{
private UserRepository $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function authenticate(string $username, string $password): ?User
{
$user = $this->userRepository->findByUsername($username);
if ($user === null) {
return null;
}
if (!password_verify($password, $user->passwordHash)) {
return null;
}
return $user;
}
public function createUser(string $username, string $password): User
{
if ($this->userRepository->findByUsername($username) !== null) {
throw new \RuntimeException("User '{$username}' already exists");
}
$user = new User();
$user->username = $username;
$user->passwordHash = password_hash($password, PASSWORD_ARGON2ID);
$user->createdAt = new \DateTimeImmutable();
$user->updatedAt = new \DateTimeImmutable();
$this->userRepository->save($user);
return $user;
}
public function getUserCount(): int
{
return $this->userRepository->count();
}
}