Merge branch 'feature/user-auth-middleware'

This commit is contained in:
Yisroel Baum 2026-05-17 10:12:10 +03:00
commit e8ab361bc6
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
38 changed files with 3342 additions and 3 deletions

3
backend/.gitignore vendored
View file

@ -1 +1,2 @@
vendor/ vendor/
.phpunit.cache/

View file

@ -0,0 +1,16 @@
<?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

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

View file

@ -0,0 +1,17 @@
<?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

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

View file

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

View file

@ -0,0 +1,42 @@
<?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

@ -0,0 +1,12 @@
<?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

@ -0,0 +1,14 @@
<?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

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

View file

@ -0,0 +1,52 @@
<?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

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

View file

@ -0,0 +1,35 @@
<?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

@ -0,0 +1,22 @@
<?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

@ -0,0 +1,152 @@
<?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

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

View file

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

View file

@ -0,0 +1,60 @@
<?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

@ -0,0 +1,47 @@
<?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

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

30
backend/app/User/User.php Normal file
View file

@ -0,0 +1,30 @@
<?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

@ -0,0 +1,14 @@
<?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

@ -20,5 +20,8 @@
"slim/slim": "4.*", "slim/slim": "4.*",
"slim/psr7": "^1.8", "slim/psr7": "^1.8",
"php-di/slim-bridge": "^3.4" "php-di/slim-bridge": "^3.4"
},
"require-dev": {
"phpunit/phpunit": "^13.1"
} }
} }

1855
backend/composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
<?php
use App\Auth\BcryptPasswordHasher;
use App\Auth\Clock;
use App\Auth\PasswordHasher;
use App\Auth\RandomTokenGenerator;
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 DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
$builder = new ContainerBuilder();
$builder->addDefinitions([
// Services
PasswordHasher::class => DI\create(BcryptPasswordHasher::class),
TokenGenerator::class => DI\create(RandomTokenGenerator::class),
Clock::class => DI\create(SystemClock::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();

17
backend/config/routes.php Normal file
View file

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

19
backend/phpunit.xml Normal file
View file

@ -0,0 +1,19 @@
<?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>

19
backend/public/index.php Normal file
View file

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

View file

@ -0,0 +1,23 @@
<?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

@ -0,0 +1,18 @@
<?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

@ -0,0 +1,46 @@
<?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

@ -0,0 +1,28 @@
<?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

@ -0,0 +1,63 @@
<?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

@ -0,0 +1,126 @@
<?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

@ -0,0 +1,102 @@
<?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

@ -0,0 +1,67 @@
<?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

@ -0,0 +1,170 @@
<?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

@ -0,0 +1,153 @@
<?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,
]);
}
}