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