Merge branch 'feature/user-auth'

This commit is contained in:
Yisroel Baum 2026-07-31 10:24:12 +03:00
commit 28c1edd958
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
28 changed files with 1039 additions and 158 deletions

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;
final readonly class CreateSessionDto
{
public function __construct(
public string $token,
public User $user,
public DateTimeImmutable $createdAt,
public DateTimeImmutable $expiresAt,
) {}
}

View file

@ -0,0 +1,62 @@
<?php
namespace App\Auth;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
class EloquentSessionRepository implements SessionRepository
{
public function __construct(
private UserRepository $userRepository,
) {}
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->userRepository->find($model->user_id);
if ($user === null) {
return null;
}
return new Session(
token: $model->token,
user: $user,
createdAt: $this->toUtc($model->created_at),
expiresAt: $this->toUtc($model->expires_at),
);
}
public function deleteByToken(string $token): void
{
SessionModel::where('token', $token)->delete();
}
private function toUtc(DateTimeImmutable $dateTime): DateTimeImmutable
{
return DateTimeImmutable::createFromInterface($dateTime)
->setTimezone(new DateTimeZone('UTC'));
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace App\Auth;
use App\User\User;
use DateTimeImmutable;
final readonly 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,50 @@
<?php
namespace App\Auth;
use DateTimeImmutable;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $token
* @property int $user_id
* @property DateTimeImmutable $created_at
* @property DateTimeImmutable $expires_at
*
* @method static Builder<static>|SessionModel newModelQuery()
* @method static Builder<static>|SessionModel newQuery()
* @method static Builder<static>|SessionModel query()
*
* @mixin \Eloquent
*/
#[Fillable([
'token',
'user_id',
'created_at',
'expires_at',
])]
class SessionModel extends Model
{
protected $table = 'sessions';
protected $primaryKey = 'token';
public $incrementing = false;
protected $keyType = 'string';
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'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,17 @@
<?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,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 string COOKIE_NAME = 'auth_token';
public function __construct(
private SessionRepository $sessionRepository,
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->sessionRepository->findByToken($token);
if ($session === null) {
return $this->unauthorized();
}
if ($session->isExpired($this->clock->now())) {
$this->sessionRepository->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

@ -1,40 +0,0 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property string $name
* @property string $email
* @property Carbon|null $email_verified_at
* @property string $password
* @property string|null $remember_token
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
use Notifiable;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View file

@ -2,6 +2,12 @@
namespace App\Providers; namespace App\Providers;
use App\Auth\Clock;
use App\Auth\EloquentSessionRepository;
use App\Auth\SessionRepository;
use App\Auth\SystemClock;
use App\User\EloquentUserRepository;
use App\User\UserRepository;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@ -15,7 +21,15 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function register(): void public function register(): void
{ {
// $this->app->bind(
UserRepository::class,
EloquentUserRepository::class,
);
$this->app->bind(
SessionRepository::class,
EloquentSessionRepository::class,
);
$this->app->bind(Clock::class, SystemClock::class);
} }
/** /**

View file

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

View file

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

View file

@ -0,0 +1,35 @@
<?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(),
]);
return $this->toDomain($model);
}
public function find(int $id): ?User
{
$model = UserModel::find($id);
if ($model === null) {
return null;
}
return $this->toDomain($model);
}
private function toDomain(UserModel $model): User
{
return new User(
id: $model->id,
email: new EmailAddress($model->email),
);
}
}

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

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

View file

@ -0,0 +1,25 @@
<?php
namespace App\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $email
*
* @method static Builder<static>|UserModel newModelQuery()
* @method static Builder<static>|UserModel newQuery()
* @method static Builder<static>|UserModel query()
*
* @mixin \Eloquent
*/
#[Fillable(['email'])]
class UserModel extends Model
{
protected $table = 'users';
public $timestamps = false;
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\User;
interface UserRepository
{
public function create(CreateUserDto $dto): User;
public function find(int $id): ?User;
}

View file

@ -1,117 +0,0 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

View file

@ -0,0 +1,21 @@
<?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): void {
$table->id();
$table->string('email')->unique();
});
}
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): void {
$table->string('token', 64)->primary();
$table->foreignId('user_id')
->constrained('users')
->cascadeOnDelete();
$table->timestamp('created_at');
$table->timestamp('expires_at')->index();
});
}
public function down(): void
{
Schema::dropIfExists('sessions');
}
};

View file

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

View file

@ -0,0 +1,38 @@
<?php
namespace Tests\Fakes;
use App\Auth\CreateSessionDto;
use App\Auth\Session;
use App\Auth\SessionRepository;
class FakeSessionRepository implements SessionRepository
{
/**
* @var array<string, 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
{
return $this->sessions[$token] ?? null;
}
public function deleteByToken(string $token): void
{
unset($this->sessions[$token]);
}
}

View file

@ -0,0 +1,119 @@
<?php
namespace Tests\Feature\Auth;
use App\Auth\Clock;
use App\Auth\CreateSessionDto;
use App\Auth\SessionRepository;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Tests\Fakes\FakeClock;
use Tests\TestCase;
class AuthMiddlewareTest extends TestCase
{
use RefreshDatabase;
private DateTimeImmutable $now;
protected function setUp(): void
{
parent::setUp();
$this->now = $this->utc('2026-07-31T12:00:00');
$this->app->instance(Clock::class, new FakeClock($this->now));
Route::middleware(AuthMiddleware::class)->get(
'/test/authenticated-user',
function (Request $request): JsonResponse {
$user = $request->attributes->get('user');
if (! $user instanceof User) {
return new JsonResponse(['error' => 'missing user'], 500);
}
return new JsonResponse([
'id' => $user->getId(),
'email' => $user->getEmail()->value(),
]);
},
);
}
public function test_valid_cookie_reaches_the_protected_route(): void
{
$user = $this->createUserAndSession(
token: 'valid-token',
expiresAt: $this->now->modify('+7 days'),
);
$response = $this->withCredentials()
->withUnencryptedCookie(
AuthMiddleware::COOKIE_NAME,
'valid-token',
)->getJson('/test/authenticated-user');
$response->assertOk()->assertExactJson([
'id' => $user->getId(),
'email' => 'user@example.com',
]);
}
public function test_missing_cookie_is_rejected(): void
{
$response = $this->getJson('/test/authenticated-user');
$response
->assertStatus(401)
->assertExactJson(['error' => 'unauthenticated']);
}
public function test_expired_cookie_is_rejected_and_deleted(): void
{
$this->createUserAndSession(
token: 'expired-token',
expiresAt: $this->now->modify('-1 day'),
);
$response = $this->withCredentials()
->withUnencryptedCookie(
AuthMiddleware::COOKIE_NAME,
'expired-token',
)->getJson('/test/authenticated-user');
$response->assertStatus(401);
$this->assertNull(
app(SessionRepository::class)->findByToken('expired-token'),
);
}
private function createUserAndSession(
string $token,
DateTimeImmutable $expiresAt,
): User {
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
));
app(SessionRepository::class)->create(new CreateSessionDto(
token: $token,
user: $user,
createdAt: $this->now,
expiresAt: $expiresAt,
));
return $user;
}
private function utc(string $time): DateTimeImmutable
{
return new DateTimeImmutable($time, new DateTimeZone('UTC'));
}
}

View file

@ -0,0 +1,85 @@
<?php
namespace Tests\Feature\Auth;
use App\Auth\CreateSessionDto;
use App\Auth\SessionRepository;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class EloquentSessionRepositoryTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_and_finds_a_session(): void
{
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
));
$createdAt = $this->utc('2026-07-31T12:00:00');
$expiresAt = $this->utc('2026-08-07T12:00:00');
$repository = app(SessionRepository::class);
$session = $repository->create(new CreateSessionDto(
token: 'session-token',
user: $user,
createdAt: $createdAt,
expiresAt: $expiresAt,
));
$this->assertSame('session-token', $session->getToken());
$this->assertSame($user, $session->getUser());
$this->assertDatabaseHas('sessions', [
'token' => 'session-token',
'user_id' => $user->getId(),
]);
$foundSession = $repository->findByToken('session-token');
$this->assertNotNull($foundSession);
$this->assertSame(
$user->getId(),
$foundSession->getUser()->getId(),
);
$this->assertEquals($createdAt, $foundSession->getCreatedAt());
$this->assertEquals($expiresAt, $foundSession->getExpiresAt());
}
public function test_it_returns_null_for_an_unknown_token(): void
{
$repository = app(SessionRepository::class);
$this->assertNull($repository->findByToken('unknown-token'));
}
public function test_it_deletes_a_session_by_token(): void
{
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
));
$repository = app(SessionRepository::class);
$repository->create(new CreateSessionDto(
token: 'session-token',
user: $user,
createdAt: $this->utc('2026-07-31T12:00:00'),
expiresAt: $this->utc('2026-08-07T12:00:00'),
));
$repository->deleteByToken('session-token');
$this->assertNull($repository->findByToken('session-token'));
$this->assertDatabaseMissing('sessions', [
'token' => 'session-token',
]);
}
private function utc(string $time): DateTimeImmutable
{
return new DateTimeImmutable($time, new DateTimeZone('UTC'));
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Tests\Feature\User;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class EloquentUserRepositoryTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_and_finds_a_user(): void
{
$repository = app(UserRepository::class);
$user = $repository->create(new CreateUserDto(
email: new EmailAddress('Founder@EXAMPLE.COM'),
));
$this->assertGreaterThan(0, $user->getId());
$this->assertSame(
'Founder@example.com',
$user->getEmail()->value(),
);
$this->assertDatabaseHas('users', [
'id' => $user->getId(),
'email' => 'Founder@example.com',
]);
$foundUser = $repository->find($user->getId());
$this->assertNotNull($foundUser);
$this->assertSame($user->getId(), $foundUser->getId());
$this->assertSame(
$user->getEmail()->value(),
$foundUser->getEmail()->value(),
);
}
public function test_it_returns_null_for_an_unknown_user(): void
{
$repository = app(UserRepository::class);
$this->assertNull($repository->find(999));
}
}

View file

@ -0,0 +1,159 @@
<?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 PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeSessionRepository;
class AuthMiddlewareTest extends TestCase
{
private FakeSessionRepository $sessionRepository;
private DateTimeImmutable $now;
private AuthMiddleware $middleware;
protected function setUp(): void
{
$this->now = new DateTimeImmutable(
'2026-07-31T12:00:00',
new DateTimeZone('UTC'),
);
$this->sessionRepository = new FakeSessionRepository;
$this->middleware = new AuthMiddleware(
sessionRepository: $this->sessionRepository,
clock: new FakeClock($this->now),
);
}
public function test_missing_cookie_returns_unauthenticated(): void
{
$capturedRequest = null;
$response = $this->middleware->handle(
$this->requestWithToken(null),
$this->captureNextRequest($capturedRequest),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertSame(
['error' => 'unauthenticated'],
json_decode($response->getContent(), true),
);
$this->assertNull($capturedRequest);
}
public function test_empty_cookie_returns_unauthenticated(): void
{
$capturedRequest = null;
$response = $this->middleware->handle(
$this->requestWithToken(''),
$this->captureNextRequest($capturedRequest),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertNull($capturedRequest);
}
public function test_unknown_token_returns_unauthenticated(): void
{
$capturedRequest = null;
$response = $this->middleware->handle(
$this->requestWithToken('unknown-token'),
$this->captureNextRequest($capturedRequest),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertNull($capturedRequest);
}
public function test_expired_session_is_deleted(): void
{
$this->sessionRepository->create(new CreateSessionDto(
token: 'expired-token',
user: $this->user(),
createdAt: $this->now->modify('-8 days'),
expiresAt: $this->now->modify('-1 day'),
));
$capturedRequest = null;
$response = $this->middleware->handle(
$this->requestWithToken('expired-token'),
$this->captureNextRequest($capturedRequest),
);
$this->assertSame(401, $response->getStatusCode());
$this->assertNull($capturedRequest);
$this->assertNull(
$this->sessionRepository->findByToken('expired-token'),
);
}
public function test_valid_session_attaches_user_and_calls_next(): void
{
$user = $this->user();
$this->sessionRepository->create(new CreateSessionDto(
token: 'valid-token',
user: $user,
createdAt: $this->now,
expiresAt: $this->now->modify('+7 days'),
));
$capturedRequest = null;
$response = $this->middleware->handle(
$this->requestWithToken('valid-token'),
$this->captureNextRequest($capturedRequest),
);
$this->assertSame(200, $response->getStatusCode());
$this->assertNotNull($capturedRequest);
$this->assertSame(
$user,
$capturedRequest->attributes->get('user'),
);
}
private function requestWithToken(?string $token): Request
{
$request = Request::create('/anything', 'GET');
if ($token !== null) {
$request->cookies->set(AuthMiddleware::COOKIE_NAME, $token);
}
return $request;
}
/**
* @param Request|null $capturedRequest
* @return Closure(Request): JsonResponse
*/
private function captureNextRequest(
?Request &$capturedRequest,
): Closure {
return function (Request $request) use (&$capturedRequest) {
$capturedRequest = $request;
return new JsonResponse(['ok' => true]);
};
}
private function user(): User
{
return new User(
id: 7,
email: new EmailAddress('user@example.com'),
);
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Tests\Unit\Auth;
use App\Auth\Session;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use DateTimeImmutable;
use DateTimeZone;
use PHPUnit\Framework\TestCase;
class SessionTest extends TestCase
{
public function test_it_exposes_its_values(): void
{
$user = new User(
id: 7,
email: new EmailAddress('user@example.com'),
);
$createdAt = $this->utc('2026-07-31T12:00:00');
$expiresAt = $this->utc('2026-08-07T12:00:00');
$session = new Session(
token: 'session-token',
user: $user,
createdAt: $createdAt,
expiresAt: $expiresAt,
);
$this->assertSame('session-token', $session->getToken());
$this->assertSame($user, $session->getUser());
$this->assertSame($createdAt, $session->getCreatedAt());
$this->assertSame($expiresAt, $session->getExpiresAt());
}
public function test_it_expires_at_the_expiry_time(): void
{
$expiresAt = $this->utc('2026-08-07T12:00:00');
$session = new Session(
token: 'session-token',
user: new User(
id: 7,
email: new EmailAddress('user@example.com'),
),
createdAt: $this->utc('2026-07-31T12:00:00'),
expiresAt: $expiresAt,
);
$this->assertFalse(
$session->isExpired($expiresAt->modify('-1 second')),
);
$this->assertTrue($session->isExpired($expiresAt));
$this->assertTrue(
$session->isExpired($expiresAt->modify('+1 second')),
);
}
private function utc(string $time): DateTimeImmutable
{
return new DateTimeImmutable($time, new DateTimeZone('UTC'));
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Tests\Unit\Shared\ValueObject;
use App\Shared\ValueObject\EmailAddress;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class EmailAddressTest extends TestCase
{
public function test_it_rejects_an_invalid_email_address(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Invalid email address: invalid-email',
);
new EmailAddress('invalid-email');
}
public function test_it_trims_and_normalizes_the_domain(): void
{
$email = new EmailAddress(' Founder@EXAMPLE.COM ');
$this->assertSame('Founder@example.com', $email->value());
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Tests\Unit\User;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase
{
public function test_it_exposes_its_identity_and_email(): void
{
$email = new EmailAddress('user@example.com');
$user = new User(id: 42, email: $email);
$this->assertSame(42, $user->getId());
$this->assertSame($email, $user->getEmail());
}
}