delete backend, starting over

This commit is contained in:
Yisroel Baum 2026-05-18 21:18:20 +03:00
parent babf9eb855
commit f6a33cf620
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
51 changed files with 0 additions and 6655 deletions

View file

@ -1,5 +0,0 @@
DB_HOST=127.0.0.1
DB_PORT=5432
DB_NAME=rabbigerzi
DB_USER=postgres
DB_PASSWORD=

3
backend/.gitignore vendored
View file

@ -1,3 +0,0 @@
vendor/
.phpunit.cache/
.env

View file

@ -1,16 +0,0 @@
<?php
namespace App\Auth;
class BcryptPasswordHasher implements PasswordHasher
{
public function hash(string $password): string
{
return password_hash($password, PASSWORD_DEFAULT);
}
public function verify(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
}

View file

@ -1,10 +0,0 @@
<?php
namespace App\Auth;
use DateTimeImmutable;
interface Clock
{
public function now(): DateTimeImmutable;
}

View file

@ -1,17 +0,0 @@
<?php
namespace App\Auth;
use App\User\User;
use DateTimeImmutable;
class CreateSessionDto
{
public function __construct(
public string $token,
public User $user,
public DateTimeImmutable $createdAt,
public DateTimeImmutable $expiresAt,
) {
}
}

View file

@ -1,10 +0,0 @@
<?php
namespace App\Auth;
interface PasswordHasher
{
public function hash(string $password): string;
public function verify(string $password, string $hash): bool;
}

View file

@ -1,64 +0,0 @@
<?php
namespace App\Auth;
use App\Database\SessionModel;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
class PostgresSessionRepository implements SessionRepository
{
public function create(CreateSessionDto $dto): Session
{
$record = SessionModel::create([
'token' => $dto->token,
'user_id' => $dto->user->getId(),
'created_at' => $dto->createdAt->format('Y-m-d H:i:s'),
'expires_at' => $dto->expiresAt->format('Y-m-d H:i:s'),
]);
return new Session(
token: $record->token,
user: $dto->user,
createdAt: $dto->createdAt,
expiresAt: $dto->expiresAt,
);
}
public function findByToken(string $token): ?Session
{
$record = SessionModel::where('token', $token)->first();
if ($record === null) {
return null;
}
$userRecord = $record->user;
if ($userRecord === null) {
return null;
}
$user = new User(
id: $userRecord->id,
email: new EmailAddress($userRecord->email),
passwordHash: $userRecord->password_hash,
);
return new Session(
token: $record->token,
user: $user,
createdAt: $record->created_at instanceof \DateTimeImmutable
? $record->created_at
: new \DateTimeImmutable($record->created_at->format('Y-m-d H:i:s')),
expiresAt: $record->expires_at instanceof \DateTimeImmutable
? $record->expires_at
: new \DateTimeImmutable($record->expires_at->format('Y-m-d H:i:s')),
);
}
public function deleteByToken(string $token): void
{
SessionModel::where('token', $token)->delete();
}
}

View file

@ -1,11 +0,0 @@
<?php
namespace App\Auth;
class RandomTokenGenerator implements TokenGenerator
{
public function generate(): string
{
return bin2hex(random_bytes(32));
}
}

View file

@ -1,42 +0,0 @@
<?php
namespace App\Auth;
use App\User\User;
use DateTimeImmutable;
class Session
{
public function __construct(
private string $token,
private User $user,
private DateTimeImmutable $createdAt,
private DateTimeImmutable $expiresAt,
) {
}
public function getToken(): string
{
return $this->token;
}
public function getUser(): User
{
return $this->user;
}
public function getCreatedAt(): DateTimeImmutable
{
return $this->createdAt;
}
public function getExpiresAt(): DateTimeImmutable
{
return $this->expiresAt;
}
public function isExpired(DateTimeImmutable $now): bool
{
return $now >= $this->expiresAt;
}
}

View file

@ -1,12 +0,0 @@
<?php
namespace App\Auth;
interface SessionRepository
{
public function create(CreateSessionDto $dto): Session;
public function findByToken(string $token): ?Session;
public function deleteByToken(string $token): void;
}

View file

@ -1,14 +0,0 @@
<?php
namespace App\Auth;
use DateTimeImmutable;
use DateTimeZone;
class SystemClock implements Clock
{
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('now', new DateTimeZone('UTC'));
}
}

View file

@ -1,8 +0,0 @@
<?php
namespace App\Auth;
interface TokenGenerator
{
public function generate(): string;
}

View file

@ -1,52 +0,0 @@
<?php
namespace App\Auth\UseCases\AuthenticateUser;
use App\Auth\PasswordHasher;
use App\Exceptions\BadRequestException;
use App\Exceptions\UnauthorizedException;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use App\User\UserRepository;
class AuthenticateUser
{
public function __construct(
private UserRepository $userRepo,
private PasswordHasher $hasher,
) {
}
/**
* @throws BadRequestException
* @throws UnauthorizedException
*/
public function execute(AuthenticateUserRequest $request): User
{
if ($request->email === null || $request->email === '') {
throw new BadRequestException('email is required');
}
if ($request->password === null || $request->password === '') {
throw new BadRequestException('password is required');
}
$user = $this->userRepo->findByEmail(
new EmailAddress($request->email),
);
if ($user === null) {
throw new UnauthorizedException('invalid credentials');
}
$passwordMatches = $this->hasher->verify(
$request->password,
$user->getPasswordHash(),
);
if (! $passwordMatches) {
throw new UnauthorizedException('invalid credentials');
}
return $user;
}
}

View file

@ -1,12 +0,0 @@
<?php
namespace App\Auth\UseCases\AuthenticateUser;
class AuthenticateUserRequest
{
public function __construct(
public ?string $email,
public ?string $password,
) {
}
}

View file

@ -1,35 +0,0 @@
<?php
namespace App\Auth\UseCases\CreateSession;
use App\Auth\Clock;
use App\Auth\CreateSessionDto;
use App\Auth\Session;
use App\Auth\SessionRepository;
use App\Auth\TokenGenerator;
use App\User\User;
class CreateSession
{
private const SESSION_LIFETIME = '+7 days';
public function __construct(
private SessionRepository $sessionRepo,
private TokenGenerator $tokenGenerator,
private Clock $clock,
) {
}
public function execute(User $user): Session
{
$now = $this->clock->now();
$expiresAt = $now->modify(self::SESSION_LIFETIME);
return $this->sessionRepo->create(new CreateSessionDto(
token: $this->tokenGenerator->generate(),
user: $user,
createdAt: $now,
expiresAt: $expiresAt,
));
}
}

View file

@ -1,22 +0,0 @@
<?php
namespace App\Auth\UseCases\Logout;
use App\Auth\SessionRepository;
class Logout
{
public function __construct(
private SessionRepository $sessionRepo,
) {
}
public function execute(?string $token): void
{
if (! is_string($token) || $token === '') {
return;
}
$this->sessionRepo->deleteByToken($token);
}
}

View file

@ -1,152 +0,0 @@
<?php
namespace App\Controllers;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUserRequest;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Auth\UseCases\Logout\Logout;
use App\Exceptions\BadRequestException;
use App\Exceptions\UnauthorizedException;
use App\Middleware\AuthMiddleware;
use App\User\User;
use DomainException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Psr7\Response;
use Throwable;
class AuthController
{
public function __construct(
private AuthenticateUser $authenticateUser,
private CreateSession $createSession,
private Logout $logout,
) {
}
public function login(
ServerRequestInterface $request,
): ResponseInterface {
$body = $this->parseBody($request);
try {
$user = $this->authenticateUser->execute(
new AuthenticateUserRequest(
email: $body['email'] ?? null,
password: $body['password'] ?? null,
),
);
} catch (Throwable $exception) {
return $this->errorResponse($exception);
}
$session = $this->createSession->execute($user);
$response = $this->jsonResponse(
['user' => $this->buildUserPayload($user)],
200,
);
$cookieValue = sprintf(
'%s=%s; Expires=%s; Path=/; HttpOnly; SameSite=Lax',
AuthMiddleware::COOKIE_NAME,
$session->getToken(),
$session->getExpiresAt()->format('D, d-M-Y H:i:s T'),
);
return $response->withHeader('Set-Cookie', $cookieValue);
}
public function logout(
ServerRequestInterface $request,
): ResponseInterface {
$cookies = $request->getCookieParams();
$token = $cookies[AuthMiddleware::COOKIE_NAME] ?? null;
$this->logout->execute($token);
$response = new Response(204);
$cookieValue = sprintf(
'%s=; Expires=%s; Path=/; HttpOnly; SameSite=Lax',
AuthMiddleware::COOKIE_NAME,
'Thu, 01-Jan-1970 00:00:00 GMT',
);
return $response->withHeader('Set-Cookie', $cookieValue);
}
public function me(
ServerRequestInterface $request,
): ResponseInterface {
$user = $request->getAttribute('user');
if (! $user instanceof User) {
return $this->jsonResponse(
['error' => 'unauthenticated'],
401,
);
}
return $this->jsonResponse(
['user' => $this->buildUserPayload($user)],
200,
);
}
private function buildUserPayload(User $user): array
{
return [
'id' => $user->getId(),
'email' => $user->getEmail()->value(),
];
}
private function jsonResponse(
array $data,
int $status,
): ResponseInterface {
$response = new Response($status);
$response->getBody()->write(json_encode($data));
return $response->withHeader('Content-Type', 'application/json');
}
private function errorResponse(Throwable $exception): ResponseInterface
{
if ($exception instanceof BadRequestException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
400,
);
}
if ($exception instanceof UnauthorizedException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
401,
);
}
if ($exception instanceof DomainException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
409,
);
}
throw $exception;
}
private function parseBody(ServerRequestInterface $request): array
{
$contentType = $request->getHeaderLine('Content-Type');
if (str_contains($contentType, 'application/json')) {
$body = (string) $request->getBody();
$decoded = json_decode($body, true);
return is_array($decoded) ? $decoded : [];
}
return (array) $request->getParsedBody();
}
}

View file

@ -1,9 +0,0 @@
<?php
namespace App\Exceptions;
use DomainException;
class BadRequestException extends DomainException
{
}

View file

@ -1,9 +0,0 @@
<?php
namespace App\Exceptions;
use DomainException;
class UnauthorizedException extends DomainException
{
}

View file

@ -1,60 +0,0 @@
<?php
namespace App\Middleware;
use App\Auth\Clock;
use App\Auth\SessionRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;
class AuthMiddleware implements MiddlewareInterface
{
public const COOKIE_NAME = 'auth_token';
public function __construct(
private SessionRepository $sessionRepo,
private Clock $clock,
) {
}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler,
): ResponseInterface {
$cookies = $request->getCookieParams();
$token = $cookies[self::COOKIE_NAME] ?? null;
if (! is_string($token) || $token === '') {
return $this->unauthorized();
}
$session = $this->sessionRepo->findByToken($token);
if ($session === null) {
return $this->unauthorized();
}
if ($session->isExpired($this->clock->now())) {
$this->sessionRepo->deleteByToken($token);
return $this->unauthorized();
}
$request = $request->withAttribute('user', $session->getUser());
return $handler->handle($request);
}
private function unauthorized(): ResponseInterface
{
$response = new Response(401);
$response->getBody()->write(
json_encode(['error' => 'unauthenticated']),
);
return $response->withHeader('Content-Type', 'application/json');
}
}

View file

@ -1,40 +0,0 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;
class CorsMiddleware implements MiddlewareInterface
{
private const ALLOWED_ORIGIN = 'http://localhost:5173';
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler,
): ResponseInterface {
if ($request->getMethod() === 'OPTIONS') {
return $this->withCorsHeaders(new Response(204));
}
return $this->withCorsHeaders($handler->handle($request));
}
private function withCorsHeaders(ResponseInterface $response): ResponseInterface
{
return $response
->withHeader('Access-Control-Allow-Origin', self::ALLOWED_ORIGIN)
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader(
'Access-Control-Allow-Headers',
'Content-Type, Authorization',
)
->withHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS',
);
}
}

View file

@ -1,47 +0,0 @@
<?php
namespace App\Shared\ValueObject;
use InvalidArgumentException;
final readonly class EmailAddress
{
private string $normalized;
private const ERROR_MESSAGE = 'Invalid email address:';
public function __construct(string $email)
{
$trimmed = trim($email);
if ($trimmed === '' || ! str_contains($trimmed, '@')) {
throw new InvalidArgumentException(self::ERROR_MESSAGE . " $email");
}
[$local, $domain] = explode('@', $trimmed, 2);
$domain = mb_strtolower($domain);
$normalized = $local . '@' . $domain;
if (filter_var($normalized, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException(self::ERROR_MESSAGE . " $email");
}
$this->normalized = $normalized;
}
public function value(): string
{
return $this->normalized;
}
public function equals(self $other): bool
{
return $this->normalized === $other->normalized;
}
public function __toString(): string
{
return $this->normalized;
}
}

View file

@ -1,14 +0,0 @@
<?php
namespace App\User;
use App\Shared\ValueObject\EmailAddress;
class CreateUserDto
{
public function __construct(
public EmailAddress $email,
public string $passwordHash,
) {
}
}

View file

@ -1,53 +0,0 @@
<?php
namespace App\User;
use App\Database\UserModel;
use App\Shared\ValueObject\EmailAddress;
class PostgresUserRepository implements UserRepository
{
public function create(CreateUserDto $dto): User
{
$record = UserModel::create([
'email' => $dto->email->value(),
'password_hash' => $dto->passwordHash,
]);
return new User(
id: $record->id,
email: new EmailAddress($record->email),
passwordHash: $record->password_hash,
);
}
public function findByEmail(EmailAddress $email): ?User
{
$record = UserModel::where('email', $email->value())->first();
if ($record === null) {
return null;
}
return new User(
id: $record->id,
email: new EmailAddress($record->email),
passwordHash: $record->password_hash,
);
}
public function find(int $id): ?User
{
$record = UserModel::find($id);
if ($record === null) {
return null;
}
return new User(
id: $record->id,
email: new EmailAddress($record->email),
passwordHash: $record->password_hash,
);
}
}

View file

@ -1,30 +0,0 @@
<?php
namespace App\User;
use App\Shared\ValueObject\EmailAddress;
class User
{
public function __construct(
private int $id,
private EmailAddress $email,
private string $passwordHash,
) {
}
public function getId(): int
{
return $this->id;
}
public function getEmail(): EmailAddress
{
return $this->email;
}
public function getPasswordHash(): string
{
return $this->passwordHash;
}
}

View file

@ -1,14 +0,0 @@
<?php
namespace App\User;
use App\Shared\ValueObject\EmailAddress;
interface UserRepository
{
public function create(CreateUserDto $dto): User;
public function findByEmail(EmailAddress $email): ?User;
public function find(int $id): ?User;
}

View file

@ -1,46 +0,0 @@
#!/usr/bin/env php
<?php
use App\Database\Migration;
(static function (): void {
$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable($root);
$dotenv->safeLoad();
require $root . '/config/database.php';
$migrationsDir = $root . '/database/migrations';
$files = glob($migrationsDir . '/*.php');
if ($files === false || $files === []) {
echo "No migration files found.\n";
exit(0);
}
sort($files);
foreach ($files as $file) {
$className = require $file;
if (! class_exists($className)) {
echo "Migration file {$file} did not define class {$className}\n";
exit(1);
}
$migration = new $className();
if (! $migration instanceof Migration) {
echo "Class {$className} must extend " . Migration::class . "\n";
exit(1);
}
echo "Running {$className}...\n";
$migration->up();
}
echo "Done.\n";
})();

View file

@ -1,40 +0,0 @@
#!/usr/bin/env php
<?php
use App\Auth\PasswordHasher;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
(static function (): void {
$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable($root);
$dotenv->safeLoad();
require $root . '/config/database.php';
$container = require $root . '/config/container.php';
$userRepo = $container->get(UserRepository::class);
$hasher = $container->get(PasswordHasher::class);
$seedEmail = 'admin@rabbigerzi.test';
$seedPassword = 'password';
$email = new EmailAddress($seedEmail);
if ($userRepo->findByEmail($email) !== null) {
echo "Seed user {$seedEmail} already exists, skipping.\n";
exit(0);
}
$userRepo->create(new CreateUserDto(
email: $email,
passwordHash: $hasher->hash($seedPassword),
));
echo "Created seed user {$seedEmail} / {$seedPassword}\n";
})();

View file

@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -e
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
export PGDATA="${PGDATA:-$REPO_ROOT/.postgres}"
export PGHOST="${PGHOST:-$PGDATA}"
export PGUSER="${PGUSER:-postgres}"
export PGDATABASE="${PGDATABASE:-rabbigerzi}"
export DB_HOST="${DB_HOST:-127.0.0.1}"
export DB_PORT="${DB_PORT:-5432}"
export DB_NAME="${DB_NAME:-rabbigerzi}"
export DB_USER="${DB_USER:-postgres}"
export DB_PASSWORD="${DB_PASSWORD:-}"
echo "[serve] waiting for postgres..."
until pg_isready -h "$PGHOST" -q 2>/dev/null; do
sleep 1
done
echo "[serve] creating database if it does not exist..."
createdb --no-password "$PGDATABASE" 2>/dev/null || echo "[serve] database already exists"
echo "[serve] running migrations..."
php "$REPO_ROOT/backend/bin/migrate"
echo "[serve] seeding..."
php "$REPO_ROOT/backend/bin/seed"
echo "[serve] starting PHP dev server..."
exec php -S 127.0.0.1:8000 -t "$REPO_ROOT/backend/public/" "$REPO_ROOT/backend/public/index.php"

View file

@ -1,30 +0,0 @@
{
"name": "pilzno/rabbigerzi",
"autoload": {
"psr-4": {
"App\\": "app/",
"App\\Database\\": "database/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"authors": [
{
"name": "Yisroel Baum",
"email": "yisroel.d.baum@gmail.com"
}
],
"require": {
"slim/slim": "4.*",
"slim/psr7": "^1.8",
"php-di/slim-bridge": "^3.4",
"illuminate/database": "^13.9",
"vlucas/phpdotenv": "^5.6"
},
"require-dev": {
"phpunit/phpunit": "^13.1"
}
}

4696
backend/composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,44 +0,0 @@
<?php
use App\Auth\BcryptPasswordHasher;
use App\Auth\Clock;
use App\Auth\PasswordHasher;
use App\Auth\PostgresSessionRepository;
use App\Auth\RandomTokenGenerator;
use App\Auth\SessionRepository;
use App\Auth\SystemClock;
use App\Auth\TokenGenerator;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Auth\UseCases\Logout\Logout;
use App\Controllers\AuthController;
use App\Middleware\AuthMiddleware;
use App\User\PostgresUserRepository;
use App\User\UserRepository;
use DI\ContainerBuilder;
$builder = new ContainerBuilder();
$builder->addDefinitions([
// Services
PasswordHasher::class => DI\create(BcryptPasswordHasher::class),
TokenGenerator::class => DI\create(RandomTokenGenerator::class),
Clock::class => DI\create(SystemClock::class),
// Repositories
UserRepository::class => DI\create(PostgresUserRepository::class),
SessionRepository::class => DI\create(PostgresSessionRepository::class),
// Use cases
AuthenticateUser::class => DI\autowire(),
CreateSession::class => DI\autowire(),
Logout::class => DI\autowire(),
// HTTP layer
AuthController::class => DI\autowire(),
AuthMiddleware::class => DI\autowire(),
]);
return $builder->build();

View file

@ -1,20 +0,0 @@
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'pgsql',
'host' => $_ENV['DB_HOST'],
'port' => $_ENV['DB_PORT'],
'database' => $_ENV['DB_NAME'],
'username' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
'charset' => 'utf8',
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
return $capsule;

View file

@ -1,20 +0,0 @@
<?php
use App\Controllers\AuthController;
use App\Middleware\AuthMiddleware;
use App\Middleware\CorsMiddleware;
use Slim\App;
use Slim\Routing\RouteCollectorProxy;
return function (App $app): void {
$app->add(CorsMiddleware::class);
$app->get('/me', [AuthController::class, 'me'])
->add(AuthMiddleware::class);
$app->post('/login', [AuthController::class, 'login']);
$app->post('/logout', [AuthController::class, 'logout'])
->add(AuthMiddleware::class);
};

View file

@ -1,18 +0,0 @@
<?php
namespace App\Database;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Builder;
abstract class Migration
{
abstract public function up(): void;
abstract public function down(): void;
protected function schema(): Builder
{
return Capsule::schema();
}
}

View file

@ -1,34 +0,0 @@
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class SessionModel extends Model
{
protected $table = 'sessions';
public $timestamps = false;
protected $primaryKey = 'token';
public $incrementing = false;
protected $fillable = [
'token',
'user_id',
'expires_at',
'created_at',
];
protected $casts = [
'expires_at' => 'datetime',
'created_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(UserModel::class, 'user_id');
}
}

View file

@ -1,21 +0,0 @@
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class UserModel extends Model
{
protected $table = 'users';
public $timestamps = true;
protected $fillable = [
'email',
'password_hash',
];
protected $casts = [
'id' => 'int',
];
}

View file

@ -1,26 +0,0 @@
<?php
namespace App\Database\Migrations;
use App\Database\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;
class CreateUsersTable extends Migration
{
public function up(): void
{
Capsule::schema()->create('users', function ($table) {
$table->increments('id');
$table->string('email', 255)->unique();
$table->string('password_hash', 255);
$table->timestamps();
});
}
public function down(): void
{
Capsule::schema()->dropIfExists('users');
}
}
return CreateUsersTable::class;

View file

@ -1,30 +0,0 @@
<?php
namespace App\Database\Migrations;
use App\Database\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;
class CreateSessionsTable extends Migration
{
public function up(): void
{
Capsule::schema()->create('sessions', function ($table) {
$table->string('token')->primary();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->cascadeOnDelete();
$table->dateTime('expires_at');
$table->dateTime('created_at');
});
}
public function down(): void
{
Capsule::schema()->dropIfExists('sessions');
}
}
return CreateSessionsTable::class;

View file

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
colors="true">
<testsuites>
<testsuite name="unit">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
</phpunit>

View file

@ -1,24 +0,0 @@
<?php
use DI\Bridge\Slim\Bridge;
use Slim\App;
(static function (): void {
$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable($root);
$dotenv->safeLoad();
require $root . '/config/database.php';
$container = require $root . '/config/container.php';
/** @var App $app */
$app = Bridge::create($container);
(require $root . '/config/routes.php')($app);
$app->run();
})();

View file

@ -1,23 +0,0 @@
<?php
namespace Tests\Fakes;
use App\Auth\Clock;
use DateTimeImmutable;
class FakeClock implements Clock
{
public function __construct(private DateTimeImmutable $currentTime)
{
}
public function now(): DateTimeImmutable
{
return $this->currentTime;
}
public function setTime(DateTimeImmutable $newTime): void
{
$this->currentTime = $newTime;
}
}

View file

@ -1,18 +0,0 @@
<?php
namespace Tests\Fakes;
use App\Auth\PasswordHasher;
class FakePasswordHasher implements PasswordHasher
{
public function hash(string $password): string
{
return 'hashed:' . $password;
}
public function verify(string $password, string $hash): bool
{
return $this->hash($password) === $hash;
}
}

View file

@ -1,46 +0,0 @@
<?php
namespace Tests\Fakes;
use App\Auth\CreateSessionDto;
use App\Auth\Session;
use App\Auth\SessionRepository;
class FakeSessionRepository implements SessionRepository
{
private array $sessions = [];
public function create(CreateSessionDto $dto): Session
{
$session = new Session(
token: $dto->token,
user: $dto->user,
createdAt: $dto->createdAt,
expiresAt: $dto->expiresAt,
);
$this->sessions[$dto->token] = $session;
return $session;
}
public function findByToken(string $token): ?Session
{
$session = $this->sessions[$token] ?? null;
if ($session === null) {
return null;
}
return new Session(
token: $session->getToken(),
user: $session->getUser(),
createdAt: $session->getCreatedAt(),
expiresAt: $session->getExpiresAt(),
);
}
public function deleteByToken(string $token): void
{
unset($this->sessions[$token]);
}
}

View file

@ -1,28 +0,0 @@
<?php
namespace Tests\Fakes;
use App\Auth\TokenGenerator;
use RuntimeException;
class FakeTokenGenerator implements TokenGenerator
{
private int $callCount = 0;
public function __construct(private array $tokens)
{
}
public function generate(): string
{
if ($this->callCount >= count($this->tokens)) {
throw new RuntimeException(
'FakeTokenGenerator exhausted'
);
}
$token = $this->tokens[$this->callCount];
$this->callCount++;
return $token;
}
}

View file

@ -1,63 +0,0 @@
<?php
namespace Tests\Fakes;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use App\User\UserRepository;
class FakeUserRepository implements UserRepository
{
private array $users = [];
public function create(CreateUserDto $dto): User
{
$id = $this->nextId();
$user = new User(
id: $id,
email: $dto->email,
passwordHash: $dto->passwordHash,
);
$this->users[$id] = $user;
return $user;
}
public function findByEmail(EmailAddress $email): ?User
{
foreach ($this->users as $user) {
if ($user->getEmail()->value() === $email->value()) {
return new User(
id: $user->getId(),
email: $user->getEmail(),
passwordHash: $user->getPasswordHash(),
);
}
}
return null;
}
public function find(int $id): ?User
{
$user = $this->users[$id] ?? null;
if ($user === null) {
return null;
}
return new User(
id: $user->getId(),
email: $user->getEmail(),
passwordHash: $user->getPasswordHash(),
);
}
private function nextId(): int
{
return count($this->users);
}
}

View file

@ -1,126 +0,0 @@
<?php
namespace Tests\Unit\Auth\UseCases;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUserRequest;
use App\Exceptions\BadRequestException;
use App\Exceptions\UnauthorizedException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeUserRepository;
class AuthenticateUserTest extends TestCase
{
private FakeUserRepository $userRepo;
private FakePasswordHasher $hasher;
private AuthenticateUser $useCase;
protected function setUp(): void
{
$this->userRepo = new FakeUserRepository();
$this->hasher = new FakePasswordHasher();
$this->useCase = new AuthenticateUser(
$this->userRepo,
$this->hasher,
);
$this->userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: $this->hasher->hash('correct-password'),
));
}
public function testAuthenticatesWithValidCredentials(): void
{
$user = $this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'correct-password',
));
$this->assertSame('user@example.com', $user->getEmail()->value());
}
public function testThrowsBadRequestWhenEmailIsEmpty(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('email is required');
$this->useCase->execute(new AuthenticateUserRequest(
email: '',
password: 'some-password',
));
}
public function testThrowsBadRequestWhenPasswordIsEmpty(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('password is required');
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: '',
));
}
public function testThrowsBadRequestWhenEmailIsNull(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('email is required');
$this->useCase->execute(new AuthenticateUserRequest(
email: null,
password: 'some-password',
));
}
public function testThrowsBadRequestWhenPasswordIsNull(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('password is required');
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: null,
));
}
public function testThrowsUnauthorizedForUnknownEmail(): void
{
$this->expectException(UnauthorizedException::class);
$this->expectExceptionMessage('invalid credentials');
$this->useCase->execute(new AuthenticateUserRequest(
email: 'unknown@example.com',
password: 'some-password',
));
}
public function testThrowsUnauthorizedForWrongPassword(): void
{
$this->expectException(UnauthorizedException::class);
$this->expectExceptionMessage('invalid credentials');
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'wrong-password',
));
}
public function testReturnsNewInstanceOnEachCall(): void
{
$user1 = $this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'correct-password',
));
$user2 = $this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'correct-password',
));
$this->assertNotSame($user1, $user2);
}
}

View file

@ -1,102 +0,0 @@
<?php
namespace Tests\Unit\Auth\UseCases;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeTokenGenerator;
use Tests\Fakes\FakeUserRepository;
class CreateSessionTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private FakeTokenGenerator $tokenGenerator;
private FakeClock $clock;
private CreateSession $useCase;
private User $user;
protected function setUp(): void
{
$this->sessionRepo = new FakeSessionRepository();
$this->tokenGenerator = new FakeTokenGenerator([
'token-1',
]);
$this->clock = new FakeClock(
new DateTimeImmutable('2026-05-16 12:00:00'),
);
$this->useCase = new CreateSession(
$this->sessionRepo,
$this->tokenGenerator,
$this->clock,
);
$userRepo = new FakeUserRepository();
$this->user = $userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed:password',
));
}
public function testCreatesSessionWithGivenToken(): void
{
$session = $this->useCase->execute($this->user);
$this->assertSame('token-1', $session->getToken());
}
public function testCreatesSessionWithUser(): void
{
$session = $this->useCase->execute($this->user);
$this->assertSame(
$this->user->getId(),
$session->getUser()->getId(),
);
}
public function testCreatesSessionWithCreatedAtFromClock(): void
{
$session = $this->useCase->execute($this->user);
$this->assertEquals(
new DateTimeImmutable('2026-05-16 12:00:00'),
$session->getCreatedAt(),
);
}
public function testCreatesSessionWithExpirySevenDaysLater(): void
{
$session = $this->useCase->execute($this->user);
$this->assertEquals(
new DateTimeImmutable('2026-05-23 12:00:00'),
$session->getExpiresAt(),
);
}
public function testPersistsSessionInRepository(): void
{
$session = $this->useCase->execute($this->user);
$found = $this->sessionRepo->findByToken('token-1');
$this->assertNotNull($found);
$this->assertSame($session->getToken(), $found->getToken());
}
public function testFreshInstanceReturnedOnEachCall(): void
{
$session = $this->useCase->execute($this->user);
$this->assertNotSame(
$session,
$this->sessionRepo->findByToken('token-1'),
);
}
}

View file

@ -1,67 +0,0 @@
<?php
namespace Tests\Unit\Auth\UseCases;
use App\Auth\CreateSessionDto;
use App\Auth\UseCases\Logout\Logout;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeUserRepository;
class LogoutTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private Logout $useCase;
protected function setUp(): void
{
$this->sessionRepo = new FakeSessionRepository();
$this->useCase = new Logout($this->sessionRepo);
$userRepo = new FakeUserRepository();
$user = $userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed:password',
));
$this->sessionRepo->create(new CreateSessionDto(
token: 'session-token',
user: $user,
createdAt: new DateTimeImmutable('2026-05-16 12:00:00'),
expiresAt: new DateTimeImmutable('2026-05-23 12:00:00'),
));
}
public function testDeletesSessionByToken(): void
{
$this->useCase->execute('session-token');
$this->assertNull(
$this->sessionRepo->findByToken('session-token'),
);
}
public function testDoesNotThrowForUnknownToken(): void
{
$this->useCase->execute('nonexistent-token');
$this->assertTrue(true);
}
public function testDoesNotThrowForNullToken(): void
{
$this->useCase->execute(null);
$this->assertTrue(true);
}
public function testDoesNotThrowForEmptyStringToken(): void
{
$this->useCase->execute('');
$this->assertTrue(true);
}
}

View file

@ -1,170 +0,0 @@
<?php
namespace Tests\Unit\Controllers;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUserRequest;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Auth\UseCases\Logout\Logout;
use App\Middleware\AuthMiddleware;
use App\Controllers\AuthController;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Psr7\Response;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeTokenGenerator;
use Tests\Fakes\FakeUserRepository;
class AuthControllerTest extends TestCase
{
private FakeUserRepository $userRepo;
private FakeSessionRepository $sessionRepo;
private FakePasswordHasher $hasher;
private FakeTokenGenerator $tokenGenerator;
private FakeClock $clock;
private AuthController $controller;
private User $user;
protected function setUp(): void
{
$this->userRepo = new FakeUserRepository();
$this->sessionRepo = new FakeSessionRepository();
$this->hasher = new FakePasswordHasher();
$this->tokenGenerator = new FakeTokenGenerator([
'session-token-1',
'session-token-2',
]);
$this->clock = new FakeClock(
new DateTimeImmutable('2026-05-16 12:00:00'),
);
$authenticateUser = new AuthenticateUser(
$this->userRepo,
$this->hasher,
);
$createSession = new CreateSession(
$this->sessionRepo,
$this->tokenGenerator,
$this->clock,
);
$logout = new Logout($this->sessionRepo);
$this->controller = new AuthController(
$authenticateUser,
$createSession,
$logout,
);
$this->user = $this->userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: $this->hasher->hash('correct-password'),
));
}
public function testLoginReturnsUserAndSetsCookie(): void
{
$request = $this->jsonRequest('POST', '/login', [
'email' => 'user@example.com',
'password' => 'correct-password',
]);
$response = $this->controller->login($request, new Response());
$this->assertSame(200, $response->getStatusCode());
$this->assertStringContainsString(
'user@example.com',
(string) $response->getBody(),
);
$cookieHeader = $response->getHeaderLine('Set-Cookie');
$this->assertStringContainsString(
AuthMiddleware::COOKIE_NAME . '=session-token-1',
$cookieHeader,
);
$this->assertStringContainsString('HttpOnly', $cookieHeader);
}
public function testLoginReturns400ForMissingEmail(): void
{
$request = $this->jsonRequest('POST', '/login', [
'password' => 'correct-password',
]);
$response = $this->controller->login($request, new Response());
$this->assertSame(400, $response->getStatusCode());
}
public function testLoginReturns401ForInvalidCredentials(): void
{
$request = $this->jsonRequest('POST', '/login', [
'email' => 'user@example.com',
'password' => 'wrong-password',
]);
$response = $this->controller->login($request, new Response());
$this->assertSame(401, $response->getStatusCode());
}
public function testLogoutClearsCookieAndReturns204(): void
{
$request = $this->createRequest()
->withCookieParams([
AuthMiddleware::COOKIE_NAME => 'session-token-1',
]);
$response = $this->controller->logout($request, new Response());
$this->assertSame(204, $response->getStatusCode());
$cookieHeader = $response->getHeaderLine('Set-Cookie');
$this->assertStringContainsString(
AuthMiddleware::COOKIE_NAME . '=',
$cookieHeader,
);
}
public function testMeReturnsUserFromAttribute(): void
{
$request = $this->createRequest()
->withAttribute('user', $this->user);
$response = $this->controller->me($request, new Response());
$this->assertSame(200, $response->getStatusCode());
$this->assertStringContainsString(
'user@example.com',
(string) $response->getBody(),
);
}
private function jsonRequest(
string $method,
string $path,
array $body,
): ServerRequestInterface {
$request = $this->createRequest($method, $path)
->withHeader('Content-Type', 'application/json');
$request->getBody()->write(json_encode($body));
$request->getBody()->rewind();
return $request;
}
private function createRequest(
string $method = 'POST',
string $path = '/',
): ServerRequestInterface {
$factory = new ServerRequestFactory();
return $factory->createServerRequest($method, $path);
}
}

View file

@ -1,153 +0,0 @@
<?php
namespace Tests\Unit\Middleware;
use App\Auth\CreateSessionDto;
use App\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Psr7\Response;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeUserRepository;
use Tests\Fakes\FakePasswordHasher;
class AuthMiddlewareTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private FakeClock $clock;
private AuthMiddleware $middleware;
private User $user;
protected function setUp(): void
{
$this->sessionRepo = new FakeSessionRepository();
$this->clock = new FakeClock(
new DateTimeImmutable('2026-05-16 12:00:00'),
);
$this->middleware = new AuthMiddleware(
$this->sessionRepo,
$this->clock,
);
$userRepo = new FakeUserRepository();
$hasher = new FakePasswordHasher();
$this->user = $userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: $hasher->hash('password'),
));
$this->sessionRepo->create(new CreateSessionDto(
token: 'valid-token',
user: $this->user,
createdAt: new DateTimeImmutable('2026-05-16 12:00:00'),
expiresAt: new DateTimeImmutable('2026-05-23 12:00:00'),
));
}
public function testPassesRequestToHandlerWhenCookieIsValid(): void
{
$request = $this->createRequestWithCookie('valid-token');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->once())
->method('handle')
->with($this->callback(function (ServerRequestInterface $request) {
$user = $request->getAttribute('user');
return $user instanceof User
&& $user->getId() === $this->user->getId();
}))
->willReturn(new Response(200));
$response = $this->middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
}
public function testReturns401WhenCookieIsMissing(): void
{
$request = self::createRequest();
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->never())->method('handle');
$response = $this->middleware->process($request, $handler);
$this->assertSame(401, $response->getStatusCode());
}
public function testReturns401WhenCookieIsEmpty(): void
{
$request = $this->createRequestWithCookie('');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->never())->method('handle');
$response = $this->middleware->process($request, $handler);
$this->assertSame(401, $response->getStatusCode());
}
public function testReturns401WhenTokenIsUnknown(): void
{
$request = $this->createRequestWithCookie('unknown-token');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->never())->method('handle');
$response = $this->middleware->process($request, $handler);
$this->assertSame(401, $response->getStatusCode());
}
public function testReturns401WhenSessionIsExpired(): void
{
$this->clock->setTime(
new DateTimeImmutable('2026-05-30 12:00:00'),
);
$request = $this->createRequestWithCookie('valid-token');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->never())->method('handle');
$response = $this->middleware->process($request, $handler);
$this->assertSame(401, $response->getStatusCode());
}
public function testDeletesExpiredSession(): void
{
$this->clock->setTime(
new DateTimeImmutable('2026-05-30 12:00:00'),
);
$request = $this->createRequestWithCookie('valid-token');
$handler = $this->createStub(RequestHandlerInterface::class);
$this->middleware->process($request, $handler);
$this->assertNull(
$this->sessionRepo->findByToken('valid-token'),
);
}
private static function createRequest(): ServerRequestInterface
{
$factory = new ServerRequestFactory();
return $factory->createServerRequest('GET', '/');
}
private function createRequestWithCookie(
string $token,
): ServerRequestInterface {
$request = self::createRequest();
return $request->withCookieParams([
AuthMiddleware::COOKIE_NAME => $token,
]);
}
}