merge user-and-auth-domains

phase 2: User + Auth foundations.

User domain: entity (id, email, passwordHash, isAdmin), dto,
repository interface, eloquent + fake impls, users migration,
SignupUser use case (validates email, length, uniqueness; hashes
password; isAdmin always false on signup).

Auth domain: Clock + TokenGenerator + PasswordHasher utility
interfaces with system + bcrypt + random impls and matching
fakes. Session entity + dto + repository interface, eloquent +
fake impls, sessions migration (token primary, fk user_id
cascade, expires_at indexed). AuthenticateUser, CreateSession,
Logout use cases. AuthMiddleware reads auth_token cookie and
attaches User to request attributes.

bindings wired in AppServiceProvider + new
RepositoryServiceProvider.

37 tests, 59 assertions; stan + cs clean.
This commit is contained in:
Yisroel Baum 2026-05-06 15:18:23 +03:00
commit 9ca58f3a9d
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
39 changed files with 1460 additions and 8 deletions

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,16 @@
<?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,60 @@
<?php
namespace App\Auth;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
class EloquentSessionRepository implements SessionRepository
{
public function __construct(private UserRepository $userRepo) {}
public function create(CreateSessionDto $dto): Session
{
SessionModel::create([
'token' => $dto->token,
'user_id' => $dto->user->getId(),
'created_at' => $dto->createdAt,
'expires_at' => $dto->expiresAt,
]);
return new Session(
token: $dto->token,
user: $dto->user,
createdAt: $dto->createdAt,
expiresAt: $dto->expiresAt,
);
}
public function findByToken(string $token): ?Session
{
$model = SessionModel::find($token);
if ($model === null) {
return null;
}
$user = $this->userRepo->find($model->user_id);
if ($user === null) {
return null;
}
$utc = new DateTimeZone('UTC');
return new Session(
token: $model->token,
user: $user,
createdAt: new DateTimeImmutable(
$model->created_at->toDateTimeString(),
$utc
),
expiresAt: new DateTimeImmutable(
$model->expires_at->toDateTimeString(),
$utc
),
);
}
public function deleteByToken(string $token): void
{
SessionModel::where('token', $token)->delete();
}
}

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,41 @@
<?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,44 @@
<?php
namespace App\Auth;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property string $token
* @property int $user_id
* @property Carbon $created_at
* @property Carbon $expires_at
*
* @method static Builder<static>|SessionModel newModelQuery()
* @method static Builder<static>|SessionModel newQuery()
* @method static Builder<static>|SessionModel query()
*
* @mixin \Eloquent
*/
class SessionModel extends Model
{
protected $table = 'sessions';
protected $primaryKey = 'token';
public $incrementing = false;
protected $keyType = 'string';
public $timestamps = false;
protected $fillable = [
'token',
'user_id',
'created_at',
'expires_at',
];
protected $casts = [
'created_at' => 'datetime',
'expires_at' => 'datetime',
];
}

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,54 @@
<?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;
use InvalidArgumentException;
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');
}
try {
$email = new EmailAddress($request->email);
} catch (InvalidArgumentException $exception) {
throw new BadRequestException($exception->getMessage());
}
$user = $this->userRepo->findByEmail($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,11 @@
<?php
namespace App\Auth\UseCases\AuthenticateUser;
class AuthenticateUserRequest
{
public function __construct(
public ?string $email,
public ?string $password,
) {}
}

View file

@ -0,0 +1,34 @@
<?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,17 @@
<?php
namespace App\Auth\UseCases\Logout;
use App\Auth\SessionRepository;
class Logout
{
public function __construct(
private SessionRepository $sessionRepo,
) {}
public function execute(string $token): void
{
$this->sessionRepo->deleteByToken($token);
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace App\Http\Middleware;
use App\Auth\Clock;
use App\Auth\SessionRepository;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthMiddleware
{
public const COOKIE_NAME = 'auth_token';
public function __construct(
private SessionRepository $sessionRepo,
private Clock $clock,
) {}
/**
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
$token = $request->cookie(self::COOKIE_NAME);
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->attributes->set('user', $session->getUser());
return $next($request);
}
private function unauthorized(): JsonResponse
{
return new JsonResponse(['error' => 'unauthenticated'], 401);
}
}

View file

@ -2,21 +2,23 @@
namespace App\Providers;
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 Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
$this->app->bind(Clock::class, SystemClock::class);
$this->app->bind(TokenGenerator::class, RandomTokenGenerator::class);
$this->app->bind(PasswordHasher::class, BcryptPasswordHasher::class);
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//

View file

@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use App\Auth\EloquentSessionRepository;
use App\Auth\SessionRepository;
use App\User\EloquentUserRepository;
use App\User\UserRepository;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(
UserRepository::class,
EloquentUserRepository::class,
);
$this->app->bind(
SessionRepository::class,
EloquentSessionRepository::class,
);
}
}

View file

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

View file

@ -0,0 +1,43 @@
<?php
namespace App\User;
use App\Shared\ValueObject\EmailAddress;
class EloquentUserRepository implements UserRepository
{
public function create(CreateUserDto $dto): User
{
$model = UserModel::create([
'email' => $dto->email->value(),
'password_hash' => $dto->passwordHash,
'is_admin' => $dto->isAdmin,
]);
return $this->toDomain($model);
}
public function find(int $id): ?User
{
$model = UserModel::find($id);
return $model === null ? null : $this->toDomain($model);
}
public function findByEmail(EmailAddress $email): ?User
{
$model = UserModel::where('email', $email->value())->first();
return $model === null ? null : $this->toDomain($model);
}
private function toDomain(UserModel $model): User
{
return new User(
id: $model->id,
email: new EmailAddress($model->email),
passwordHash: $model->password_hash,
isAdmin: $model->is_admin,
);
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace App\User\UseCases\SignupUser;
use App\Auth\PasswordHasher;
use App\Exceptions\BadRequestException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use App\User\UserRepository;
use DomainException;
use InvalidArgumentException;
class SignupUser
{
private const MIN_PASSWORD_LENGTH = 8;
public function __construct(
private UserRepository $userRepo,
private PasswordHasher $hasher,
) {}
/**
* @throws BadRequestException
* @throws DomainException
*/
public function execute(SignupUserRequest $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');
}
if (strlen($request->password) < self::MIN_PASSWORD_LENGTH) {
throw new BadRequestException(
'password must be at least '.self::MIN_PASSWORD_LENGTH.' characters'
);
}
try {
$email = new EmailAddress($request->email);
} catch (InvalidArgumentException $exception) {
throw new BadRequestException($exception->getMessage());
}
if ($this->userRepo->findByEmail($email) !== null) {
throw new DomainException('email already registered');
}
return $this->userRepo->create(new CreateUserDto(
email: $email,
passwordHash: $this->hasher->hash($request->password),
isAdmin: false,
));
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace App\User\UseCases\SignupUser;
class SignupUserRequest
{
public function __construct(
public ?string $email,
public ?string $password,
) {}
}

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

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

View file

@ -0,0 +1,38 @@
<?php
namespace App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $email
* @property string $password_hash
* @property bool $is_admin
*
* @method static Builder<static>|UserModel newModelQuery()
* @method static Builder<static>|UserModel newQuery()
* @method static Builder<static>|UserModel query()
* @method static Builder<static>|UserModel whereId($value)
* @method static Builder<static>|UserModel whereEmail($value)
* @method static Builder<static>|UserModel whereIsAdmin($value)
*
* @mixin \Eloquent
*/
class UserModel extends Model
{
protected $table = 'users';
public $timestamps = false;
protected $fillable = [
'email',
'password_hash',
'is_admin',
];
protected $casts = [
'is_admin' => 'boolean',
];
}

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 find(int $id): ?User;
public function findByEmail(EmailAddress $email): ?User;
}

View file

@ -1,7 +1,9 @@
<?php
use App\Providers\AppServiceProvider;
use App\Providers\RepositoryServiceProvider;
return [
AppServiceProvider::class,
RepositoryServiceProvider::class,
];

View file

@ -49,7 +49,7 @@
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" --names=server,queue,logs --kill-others"
],
"stan": "phpstan analyse",
"stan": "phpstan analyse --no-progress --memory-limit=512M",
"cs:fix": "php-cs-fixer fix",
"cs:check": "php-cs-fixer check --diff -vvv",

View file

@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->string('password_hash');
$table->boolean('is_admin')->default(false);
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
};

View file

@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('sessions', function (Blueprint $table) {
$table->string('token')->primary();
$table->foreignId('user_id')
->constrained('users')
->cascadeOnDelete();
$table->dateTime('created_at');
$table->dateTime('expires_at')->index();
});
}
public function down(): void
{
Schema::dropIfExists('sessions');
}
};

View file

@ -0,0 +1,21 @@
<?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,48 @@
<?php
namespace Tests\Fakes;
use App\Auth\CreateSessionDto;
use App\Auth\Session;
use App\Auth\SessionRepository;
class FakeSessionRepository implements SessionRepository
{
/**
* @var Session[]
*/
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,27 @@
<?php
namespace Tests\Fakes;
use App\Auth\TokenGenerator;
use RuntimeException;
class FakeTokenGenerator implements TokenGenerator
{
private int $callCount = 0;
/**
* @param string[] $tokens
*/
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,66 @@
<?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
{
/**
* @var User[]
*/
private array $existingUsers = [];
public function create(CreateUserDto $dto): User
{
$id = $this->getNextId();
$user = new User(
id: $id,
email: $dto->email,
passwordHash: $dto->passwordHash,
isAdmin: $dto->isAdmin,
);
$this->existingUsers[$id] = $user;
return $user;
}
public function find(int $id): ?User
{
$user = $this->existingUsers[$id] ?? null;
if ($user === null) {
return null;
}
return new User(
id: $user->getId(),
email: $user->getEmail(),
passwordHash: $user->getPasswordHash(),
isAdmin: $user->isAdmin(),
);
}
public function findByEmail(EmailAddress $email): ?User
{
foreach ($this->existingUsers as $user) {
if ($user->getEmail()->equals($email)) {
return new User(
id: $user->getId(),
email: $user->getEmail(),
passwordHash: $user->getPasswordHash(),
isAdmin: $user->isAdmin(),
);
}
}
return null;
}
private function getNextId(): int
{
return count($this->existingUsers) + 1;
}
}

View file

@ -0,0 +1,142 @@
<?php
namespace Tests\Unit\Auth\Middleware;
use App\Auth\CreateSessionDto;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use Closure;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeSessionRepository;
use Tests\TestCase;
class AuthMiddlewareTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private FakeClock $clock;
private DateTimeImmutable $now;
private AuthMiddleware $middleware;
protected function setUp(): void
{
$this->now = new DateTimeImmutable(
'2026-05-06T12:00:00',
new DateTimeZone('UTC')
);
$this->sessionRepo = new FakeSessionRepository;
$this->clock = new FakeClock($this->now);
$this->middleware = new AuthMiddleware(
$this->sessionRepo,
$this->clock,
);
}
private function makeRequest(?string $token): Request
{
$request = Request::create('/api/anything', 'POST');
if ($token !== null) {
$request->cookies->set('auth_token', $token);
}
return $request;
}
private function nextThatRecords(?Request &$captured): Closure
{
return function (Request $request) use (&$captured) {
$captured = $request;
return new JsonResponse(['ok' => true], 200);
};
}
private function makeUser(int $id = 7): User
{
return new User(
id: $id,
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed:irrelevant',
isAdmin: false,
);
}
public function test_missing_cookie_returns_unauthorized_json(): void
{
$captured = null;
$response = $this->middleware->handle(
$this->makeRequest(null),
$this->nextThatRecords($captured),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertSame(
['error' => 'unauthenticated'],
json_decode($response->getContent(), true),
);
$this->assertNull($captured);
}
public function test_unknown_token_returns_unauthorized(): void
{
$captured = null;
$response = $this->middleware->handle(
$this->makeRequest('does-not-exist'),
$this->nextThatRecords($captured),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertNull($captured);
}
public function test_expired_session_returns_unauthorized_and_is_deleted(): void
{
$this->sessionRepo->create(new CreateSessionDto(
token: 'expired-token',
user: $this->makeUser(),
createdAt: $this->now->modify('-8 days'),
expiresAt: $this->now->modify('-1 day'),
));
$captured = null;
$response = $this->middleware->handle(
$this->makeRequest('expired-token'),
$this->nextThatRecords($captured),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertNull($captured);
$this->assertNull(
$this->sessionRepo->findByToken('expired-token')
);
}
public function test_valid_session_attaches_user_and_calls_next(): void
{
$this->sessionRepo->create(new CreateSessionDto(
token: 'valid-token',
user: $this->makeUser(id: 7),
createdAt: $this->now,
expiresAt: $this->now->modify('+7 days'),
));
$captured = null;
$response = $this->middleware->handle(
$this->makeRequest('valid-token'),
$this->nextThatRecords($captured),
);
$this->assertSame(200, $response->getStatusCode());
$this->assertNotNull($captured);
$attachedUser = $captured->attributes->get('user');
$this->assertInstanceOf(User::class, $attachedUser);
$this->assertSame(7, $attachedUser->getId());
}
}

View file

@ -0,0 +1,156 @@
<?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 App\User\User;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeUserRepository;
use Tests\TestCase;
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,
);
}
private function seedUser(
string $email,
string $password,
bool $isAdmin,
): User {
return $this->userRepo->create(new CreateUserDto(
email: new EmailAddress($email),
passwordHash: $this->hasher->hash($password),
isAdmin: $isAdmin,
));
}
public function test_null_email_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: null,
password: 'correctpassword',
));
}
public function test_empty_email_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: '',
password: 'correctpassword',
));
}
public function test_null_password_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: null,
));
}
public function test_empty_password_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: '',
));
}
public function test_malformed_email_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: 'not-an-email',
password: 'correctpassword',
));
}
public function test_unknown_email_throws_unauthorized(): void
{
$this->expectException(UnauthorizedException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: 'nobody@example.com',
password: 'correctpassword',
));
}
public function test_wrong_password_throws_unauthorized(): void
{
$this->seedUser(
email: 'user@example.com',
password: 'correctpassword',
isAdmin: false,
);
$this->expectException(UnauthorizedException::class);
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'wrongpassword',
));
}
public function test_valid_credentials_return_user(): void
{
$seeded = $this->seedUser(
email: 'user@example.com',
password: 'correctpassword',
isAdmin: false,
);
$authenticated = $this->useCase->execute(
new AuthenticateUserRequest(
email: 'user@example.com',
password: 'correctpassword',
)
);
$this->assertInstanceOf(User::class, $authenticated);
$this->assertSame($seeded->getId(), $authenticated->getId());
$this->assertSame(
'user@example.com',
$authenticated->getEmail()->value(),
);
$this->assertFalse($authenticated->isAdmin());
}
public function test_admin_flag_is_preserved_on_authentication(): void
{
$this->seedUser(
email: 'admin@example.com',
password: 'adminpassword',
isAdmin: true,
);
$authenticated = $this->useCase->execute(
new AuthenticateUserRequest(
email: 'admin@example.com',
password: 'adminpassword',
)
);
$this->assertTrue($authenticated->isAdmin());
}
}

View file

@ -0,0 +1,86 @@
<?php
namespace Tests\Unit\Auth\UseCases;
use App\Auth\Session;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use DateTimeImmutable;
use DateTimeZone;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeTokenGenerator;
use Tests\TestCase;
class CreateSessionTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private FakeTokenGenerator $tokenGenerator;
private FakeClock $clock;
private DateTimeImmutable $now;
private CreateSession $useCase;
protected function setUp(): void
{
$this->now = new DateTimeImmutable(
'2026-05-06T12:00:00',
new DateTimeZone('UTC')
);
$this->sessionRepo = new FakeSessionRepository;
$this->tokenGenerator = new FakeTokenGenerator(['token-abc']);
$this->clock = new FakeClock($this->now);
$this->useCase = new CreateSession(
$this->sessionRepo,
$this->tokenGenerator,
$this->clock,
);
}
private function makeUser(): User
{
return new User(
id: 7,
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed:irrelevant',
isAdmin: false,
);
}
public function test_creates_session_with_generated_token(): void
{
$session = $this->useCase->execute($this->makeUser());
$this->assertInstanceOf(Session::class, $session);
$this->assertSame('token-abc', $session->getToken());
$this->assertSame(7, $session->getUser()->getId());
}
public function test_session_created_at_is_clock_now(): void
{
$session = $this->useCase->execute($this->makeUser());
$this->assertEquals($this->now, $session->getCreatedAt());
}
public function test_session_expires_seven_days_from_now(): void
{
$session = $this->useCase->execute($this->makeUser());
$expected = $this->now->modify('+7 days');
$this->assertEquals($expected, $session->getExpiresAt());
}
public function test_session_is_findable_by_token(): void
{
$this->useCase->execute($this->makeUser());
$found = $this->sessionRepo->findByToken('token-abc');
$this->assertNotNull($found);
$this->assertSame(7, $found->getUser()->getId());
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Tests\Unit\Auth\UseCases;
use App\Auth\CreateSessionDto;
use App\Auth\UseCases\Logout\Logout;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use DateTimeImmutable;
use DateTimeZone;
use Tests\Fakes\FakeSessionRepository;
use Tests\TestCase;
class LogoutTest extends TestCase
{
private FakeSessionRepository $sessionRepo;
private Logout $useCase;
private DateTimeImmutable $now;
protected function setUp(): void
{
$this->now = new DateTimeImmutable(
'2026-05-06T12:00:00',
new DateTimeZone('UTC')
);
$this->sessionRepo = new FakeSessionRepository;
$this->useCase = new Logout($this->sessionRepo);
}
public function test_existing_token_session_is_removed(): void
{
$user = new User(
id: 7,
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed:irrelevant',
isAdmin: false,
);
$this->sessionRepo->create(new CreateSessionDto(
token: 'token-abc',
user: $user,
createdAt: $this->now,
expiresAt: $this->now->modify('+7 days'),
));
$this->useCase->execute('token-abc');
$this->assertNull($this->sessionRepo->findByToken('token-abc'));
}
public function test_unknown_token_does_not_throw(): void
{
$this->useCase->execute('unknown-token');
$this->assertNull($this->sessionRepo->findByToken('unknown-token'));
}
}

View file

@ -0,0 +1,133 @@
<?php
namespace Tests\Unit\User\UseCases;
use App\Exceptions\BadRequestException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UseCases\SignupUser\SignupUser;
use App\User\UseCases\SignupUser\SignupUserRequest;
use App\User\User;
use DomainException;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeUserRepository;
use Tests\TestCase;
class SignupUserTest extends TestCase
{
private FakeUserRepository $userRepo;
private FakePasswordHasher $hasher;
private SignupUser $useCase;
protected function setUp(): void
{
$this->userRepo = new FakeUserRepository;
$this->hasher = new FakePasswordHasher;
$this->useCase = new SignupUser(
$this->userRepo,
$this->hasher,
);
}
public function test_null_email_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new SignupUserRequest(
email: null,
password: 'longenoughpassword',
));
}
public function test_empty_email_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new SignupUserRequest(
email: '',
password: 'longenoughpassword',
));
}
public function test_invalid_email_format_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new SignupUserRequest(
email: 'not-an-email',
password: 'longenoughpassword',
));
}
public function test_null_password_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new SignupUserRequest(
email: 'user@example.com',
password: null,
));
}
public function test_short_password_throws_bad_request(): void
{
$this->expectException(BadRequestException::class);
$this->useCase->execute(new SignupUserRequest(
email: 'user@example.com',
password: 'short',
));
}
public function test_duplicate_email_throws_domain_exception(): void
{
$this->userRepo->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: $this->hasher->hash('original-password'),
isAdmin: false,
));
$this->expectException(DomainException::class);
$this->useCase->execute(new SignupUserRequest(
email: 'user@example.com',
password: 'second-attempt-password',
));
}
public function test_valid_signup_returns_user_with_hashed_password(): void
{
$created = $this->useCase->execute(new SignupUserRequest(
email: 'new@example.com',
password: 'longenoughpassword',
));
$this->assertInstanceOf(User::class, $created);
$this->assertSame('new@example.com', $created->getEmail()->value());
$this->assertSame(
$this->hasher->hash('longenoughpassword'),
$created->getPasswordHash(),
);
$this->assertFalse($created->isAdmin());
}
public function test_created_user_is_findable_by_email(): void
{
$created = $this->useCase->execute(new SignupUserRequest(
email: 'lookup@example.com',
password: 'longenoughpassword',
));
$found = $this->userRepo->findByEmail(
new EmailAddress('lookup@example.com')
);
$this->assertNotNull($found);
$this->assertSame($created->getId(), $found->getId());
}
public function test_signup_normalizes_email_domain(): void
{
$created = $this->useCase->execute(new SignupUserRequest(
email: 'Mixed@CASE.com',
password: 'longenoughpassword',
));
$this->assertSame('Mixed@case.com', $created->getEmail()->value());
}
}