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,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;
}