add Session entity, persistence, fake
Session: immutable holder of token, owning User, createdAt, expiresAt. isExpired(now) compares >= expiresAt. SessionModel keys on token (string primary, non-incrementing). migration adds sessions table with foreign user_id (cascade on user delete) and indexed expires_at for cleanup queries. EloquentSessionRepository takes UserRepository to rehydrate the owning User on findByToken; sessions for deleted users return null. FakeSessionRepository mirrors with an in-memory map keyed by token, defensive copies on read.
This commit is contained in:
parent
bb38e544ee
commit
05f935f275
7 changed files with 246 additions and 0 deletions
60
backend/app/Auth/EloquentSessionRepository.php
Normal file
60
backend/app/Auth/EloquentSessionRepository.php
Normal 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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue