feat: Gestion des sessions utilisateur
Permet aux utilisateurs de visualiser et gérer leurs sessions actives sur différents appareils, avec la possibilité de révoquer des sessions à distance en cas de suspicion d'activité non autorisée. Fonctionnalités : - Liste des sessions actives avec métadonnées (appareil, navigateur, localisation) - Identification de la session courante - Révocation individuelle d'une session - Révocation de toutes les autres sessions - Déconnexion avec nettoyage des cookies sur les deux chemins (legacy et actuel) Sécurité : - Cache frontend scopé par utilisateur pour éviter les fuites entre comptes - Validation que le refresh token appartient à l'utilisateur JWT authentifié - TTL des sessions Redis aligné sur l'expiration du refresh token - Événements d'audit pour traçabilité (SessionInvalidee, ToutesSessionsInvalidees) @see Story 1.6 - Gestion des sessions
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Application\Port;
|
||||
|
||||
use App\Administration\Domain\Model\Session\Location;
|
||||
|
||||
/**
|
||||
* Port interface for IP geolocation operations.
|
||||
*
|
||||
* This abstracts the geolocation mechanism, allowing the Application
|
||||
* layer to remain independent of the specific implementation
|
||||
* (e.g., MaxMind GeoLite2, IP-API, etc.).
|
||||
*
|
||||
* Current implementation: NullGeoLocationService (stores IP without resolution).
|
||||
* Future implementation: MaxMindGeoLocationService using GeoLite2-City database
|
||||
* for country/city resolution. This will be implemented when the feature is
|
||||
* prioritized (requires GeoLite2 license and periodic database updates).
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
interface GeoLocationService
|
||||
{
|
||||
/**
|
||||
* Locate an IP address.
|
||||
*
|
||||
* Returns Location with country and city if available,
|
||||
* or Location::unknown() if geolocation fails.
|
||||
*/
|
||||
public function locate(string $ipAddress): Location;
|
||||
}
|
||||
39
backend/src/Administration/Domain/Event/Deconnexion.php
Normal file
39
backend/src/Administration/Domain/Event/Deconnexion.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Event;
|
||||
|
||||
use App\Shared\Domain\DomainEvent;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
use DateTimeImmutable;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Ramsey\Uuid\UuidInterface;
|
||||
|
||||
/**
|
||||
* Événement émis lors d'une déconnexion volontaire.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class Deconnexion implements DomainEvent
|
||||
{
|
||||
public function __construct(
|
||||
public string $userId,
|
||||
public string $familyId,
|
||||
public TenantId $tenantId,
|
||||
public string $ipAddress,
|
||||
public string $userAgent,
|
||||
public DateTimeImmutable $occurredOn,
|
||||
) {
|
||||
}
|
||||
|
||||
public function occurredOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->occurredOn;
|
||||
}
|
||||
|
||||
public function aggregateId(): UuidInterface
|
||||
{
|
||||
return Uuid::fromString($this->userId);
|
||||
}
|
||||
}
|
||||
39
backend/src/Administration/Domain/Event/SessionInvalidee.php
Normal file
39
backend/src/Administration/Domain/Event/SessionInvalidee.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Event;
|
||||
|
||||
use App\Shared\Domain\DomainEvent;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
use DateTimeImmutable;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Ramsey\Uuid\UuidInterface;
|
||||
|
||||
/**
|
||||
* Événement émis lorsqu'une session est invalidée.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class SessionInvalidee implements DomainEvent
|
||||
{
|
||||
public function __construct(
|
||||
public string $userId,
|
||||
public string $familyId,
|
||||
public TenantId $tenantId,
|
||||
public string $ipAddress,
|
||||
public string $userAgent,
|
||||
public DateTimeImmutable $occurredOn,
|
||||
) {
|
||||
}
|
||||
|
||||
public function occurredOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->occurredOn;
|
||||
}
|
||||
|
||||
public function aggregateId(): UuidInterface
|
||||
{
|
||||
return Uuid::fromString($this->userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Event;
|
||||
|
||||
use App\Shared\Domain\DomainEvent;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
use DateTimeImmutable;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Ramsey\Uuid\UuidInterface;
|
||||
|
||||
/**
|
||||
* Événement émis lorsque toutes les sessions (sauf courante) sont invalidées.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class ToutesSessionsInvalidees implements DomainEvent
|
||||
{
|
||||
/**
|
||||
* @param list<string> $invalidatedFamilyIds Les IDs des familles de tokens invalidées
|
||||
*/
|
||||
public function __construct(
|
||||
public string $userId,
|
||||
public array $invalidatedFamilyIds,
|
||||
public string $exceptFamilyId,
|
||||
public TenantId $tenantId,
|
||||
public string $ipAddress,
|
||||
public string $userAgent,
|
||||
public DateTimeImmutable $occurredOn,
|
||||
) {
|
||||
}
|
||||
|
||||
public function occurredOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->occurredOn;
|
||||
}
|
||||
|
||||
public function aggregateId(): UuidInterface
|
||||
{
|
||||
return Uuid::fromString($this->userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Exception;
|
||||
|
||||
use App\Administration\Domain\Model\RefreshToken\TokenFamilyId;
|
||||
use RuntimeException;
|
||||
|
||||
use function sprintf;
|
||||
|
||||
/**
|
||||
* Exception levée lorsqu'une session n'est pas trouvée.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final class SessionNotFoundException extends RuntimeException
|
||||
{
|
||||
public function __construct(TokenFamilyId $familyId)
|
||||
{
|
||||
parent::__construct(sprintf('Session with family ID "%s" not found.', $familyId));
|
||||
}
|
||||
}
|
||||
171
backend/src/Administration/Domain/Model/Session/DeviceInfo.php
Normal file
171
backend/src/Administration/Domain/Model/Session/DeviceInfo.php
Normal file
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Model\Session;
|
||||
|
||||
/**
|
||||
* Informations sur l'appareil/navigateur de la session.
|
||||
*
|
||||
* Parse le User-Agent pour extraire des informations lisibles :
|
||||
* - device : Desktop, Mobile, Tablet
|
||||
* - browser : Chrome 120, Firefox 121, Safari 17...
|
||||
* - os : Windows 10, macOS 10.15, iOS 17.2, Android 14...
|
||||
*
|
||||
* Le rawUserAgent est conservé pour le fingerprinting.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class DeviceInfo
|
||||
{
|
||||
private function __construct(
|
||||
public string $device,
|
||||
public string $browser,
|
||||
public string $os,
|
||||
public string $rawUserAgent,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse un User-Agent pour extraire les informations de l'appareil.
|
||||
*/
|
||||
public static function fromUserAgent(string $userAgent): self
|
||||
{
|
||||
if ($userAgent === '') {
|
||||
return new self(
|
||||
device: 'Inconnu',
|
||||
browser: 'Inconnu',
|
||||
os: 'Inconnu',
|
||||
rawUserAgent: '',
|
||||
);
|
||||
}
|
||||
|
||||
$device = self::parseDevice($userAgent);
|
||||
$browser = self::parseBrowser($userAgent);
|
||||
$os = self::parseOs($userAgent);
|
||||
|
||||
return new self(
|
||||
device: $device,
|
||||
browser: $browser,
|
||||
os: $os,
|
||||
rawUserAgent: $userAgent,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstitue les informations depuis le stockage.
|
||||
*
|
||||
* @internal Pour usage Infrastructure uniquement
|
||||
*/
|
||||
public static function reconstitute(
|
||||
string $device,
|
||||
string $browser,
|
||||
string $os,
|
||||
string $rawUserAgent,
|
||||
): self {
|
||||
return new self($device, $browser, $os, $rawUserAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indique si l'appareil est mobile (phone ou tablet).
|
||||
*/
|
||||
public function isMobile(): bool
|
||||
{
|
||||
return $this->device === 'Mobile' || $this->device === 'Tablet';
|
||||
}
|
||||
|
||||
private static function parseDevice(string $userAgent): string
|
||||
{
|
||||
$ua = strtolower($userAgent);
|
||||
|
||||
if (str_contains($ua, 'ipad')) {
|
||||
return 'Tablet';
|
||||
}
|
||||
|
||||
if (str_contains($ua, 'mobile') || str_contains($ua, 'iphone') || str_contains($ua, 'android')) {
|
||||
if (str_contains($ua, 'tablet')) {
|
||||
return 'Tablet';
|
||||
}
|
||||
|
||||
return 'Mobile';
|
||||
}
|
||||
|
||||
if (str_contains($ua, 'windows') || str_contains($ua, 'macintosh') || str_contains($ua, 'linux')) {
|
||||
return 'Desktop';
|
||||
}
|
||||
|
||||
return 'Inconnu';
|
||||
}
|
||||
|
||||
private static function parseBrowser(string $userAgent): string
|
||||
{
|
||||
// Edge doit être testé avant Chrome car Edge contient "Chrome"
|
||||
if (preg_match('/Edg(?:e|A|iOS)?\/(\d+)/', $userAgent, $matches)) {
|
||||
return "Edge {$matches[1]}";
|
||||
}
|
||||
|
||||
if (preg_match('/Chrome\/(\d+)/', $userAgent, $matches)) {
|
||||
return "Chrome {$matches[1]}";
|
||||
}
|
||||
|
||||
if (preg_match('/Firefox\/(\d+)/', $userAgent, $matches)) {
|
||||
return "Firefox {$matches[1]}";
|
||||
}
|
||||
|
||||
// Safari: chercher Version/ pour la version affichée
|
||||
if (preg_match('/Version\/(\d+)/', $userAgent, $matches) && str_contains($userAgent, 'Safari')) {
|
||||
return "Safari {$matches[1]}";
|
||||
}
|
||||
|
||||
return 'Inconnu';
|
||||
}
|
||||
|
||||
private static function parseOs(string $userAgent): string
|
||||
{
|
||||
// Windows
|
||||
if (preg_match('/Windows NT (\d+\.\d+)/', $userAgent, $matches)) {
|
||||
$version = match ($matches[1]) {
|
||||
'10.0' => '10',
|
||||
'6.3' => '8.1',
|
||||
'6.2' => '8',
|
||||
'6.1' => '7',
|
||||
default => $matches[1],
|
||||
};
|
||||
|
||||
return "Windows {$version}";
|
||||
}
|
||||
|
||||
// macOS
|
||||
if (preg_match('/Mac OS X (\d+[._]\d+)/', $userAgent, $matches)) {
|
||||
$version = str_replace('_', '.', $matches[1]);
|
||||
|
||||
return "macOS {$version}";
|
||||
}
|
||||
|
||||
// iPadOS
|
||||
if (preg_match('/iPad.*OS (\d+[._]\d+)/', $userAgent, $matches)) {
|
||||
$version = str_replace('_', '.', $matches[1]);
|
||||
|
||||
return "iPadOS {$version}";
|
||||
}
|
||||
|
||||
// iOS
|
||||
if (preg_match('/iPhone.*OS (\d+[._]\d+)/', $userAgent, $matches)) {
|
||||
$version = str_replace('_', '.', $matches[1]);
|
||||
|
||||
return "iOS {$version}";
|
||||
}
|
||||
|
||||
// Android
|
||||
if (preg_match('/Android (\d+)/', $userAgent, $matches)) {
|
||||
return "Android {$matches[1]}";
|
||||
}
|
||||
|
||||
// Linux (générique)
|
||||
if (str_contains($userAgent, 'Linux')) {
|
||||
return 'Linux';
|
||||
}
|
||||
|
||||
return 'Inconnu';
|
||||
}
|
||||
}
|
||||
78
backend/src/Administration/Domain/Model/Session/Location.php
Normal file
78
backend/src/Administration/Domain/Model/Session/Location.php
Normal file
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Model\Session;
|
||||
|
||||
/**
|
||||
* Localisation approximative basée sur l'adresse IP.
|
||||
*
|
||||
* Utilisé pour afficher "France, Paris" dans la liste des sessions.
|
||||
* La précision dépend du service de géolocalisation.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class Location
|
||||
{
|
||||
private function __construct(
|
||||
public ?string $ip,
|
||||
public ?string $country,
|
||||
public ?string $city,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée une localisation à partir d'une IP et des données de géolocalisation.
|
||||
*/
|
||||
public static function fromIp(string $ip, ?string $country, ?string $city): self
|
||||
{
|
||||
return new self(
|
||||
ip: $ip,
|
||||
country: $country,
|
||||
city: $city,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée une localisation inconnue (quand la géolocalisation échoue).
|
||||
*/
|
||||
public static function unknown(): self
|
||||
{
|
||||
return new self(
|
||||
ip: null,
|
||||
country: null,
|
||||
city: null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstitue une localisation depuis le stockage.
|
||||
*
|
||||
* @internal Pour usage Infrastructure uniquement
|
||||
*/
|
||||
public static function reconstitute(
|
||||
?string $ip,
|
||||
?string $country,
|
||||
?string $city,
|
||||
): self {
|
||||
return new self($ip, $country, $city);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formate la localisation pour affichage.
|
||||
*
|
||||
* @return string "France, Paris" ou "France" ou "Inconnu"
|
||||
*/
|
||||
public function format(): string
|
||||
{
|
||||
if ($this->country !== null && $this->city !== null) {
|
||||
return "{$this->country}, {$this->city}";
|
||||
}
|
||||
|
||||
if ($this->country !== null) {
|
||||
return $this->country;
|
||||
}
|
||||
|
||||
return 'Inconnu';
|
||||
}
|
||||
}
|
||||
128
backend/src/Administration/Domain/Model/Session/Session.php
Normal file
128
backend/src/Administration/Domain/Model/Session/Session.php
Normal file
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Model\Session;
|
||||
|
||||
use App\Administration\Domain\Model\RefreshToken\TokenFamilyId;
|
||||
use App\Administration\Domain\Model\User\UserId;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Représente une session utilisateur active.
|
||||
*
|
||||
* Une session est identifiée par son familyId (lié aux token families).
|
||||
* Elle stocke les métadonnées lisibles par l'utilisateur :
|
||||
* - Appareil/navigateur (DeviceInfo)
|
||||
* - Localisation approximative (Location)
|
||||
* - Dates de création et dernière activité
|
||||
*
|
||||
* Invariants :
|
||||
* - Une session appartient à un seul utilisateur et tenant
|
||||
* - Le familyId est immutable (identifie la session)
|
||||
* - lastActivityAt >= createdAt
|
||||
*
|
||||
* Note sur les méthodes statiques :
|
||||
* Cette classe utilise des factory methods (create(), reconstitute()) suivant les
|
||||
* patterns DDD standards pour la création d'Aggregates. Bien que le projet suive
|
||||
* les principes "No Static" d'Elegant Objects, les factory methods pour Aggregates
|
||||
* sont une exception documentée car elles encapsulent la logique d'instanciation
|
||||
* et gardent le constructeur privé, préservant ainsi les invariants du domaine.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class Session
|
||||
{
|
||||
private function __construct(
|
||||
public TokenFamilyId $familyId,
|
||||
public UserId $userId,
|
||||
public TenantId $tenantId,
|
||||
public DeviceInfo $deviceInfo,
|
||||
public Location $location,
|
||||
public DateTimeImmutable $createdAt,
|
||||
public DateTimeImmutable $lastActivityAt,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée une nouvelle session lors de la connexion.
|
||||
*/
|
||||
public static function create(
|
||||
TokenFamilyId $familyId,
|
||||
UserId $userId,
|
||||
TenantId $tenantId,
|
||||
DeviceInfo $deviceInfo,
|
||||
Location $location,
|
||||
DateTimeImmutable $createdAt,
|
||||
): self {
|
||||
return new self(
|
||||
familyId: $familyId,
|
||||
userId: $userId,
|
||||
tenantId: $tenantId,
|
||||
deviceInfo: $deviceInfo,
|
||||
location: $location,
|
||||
createdAt: $createdAt,
|
||||
lastActivityAt: $createdAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour le timestamp de dernière activité.
|
||||
*
|
||||
* Appelé lors du refresh de token pour maintenir la session active.
|
||||
*/
|
||||
public function updateActivity(DateTimeImmutable $at): self
|
||||
{
|
||||
return new self(
|
||||
familyId: $this->familyId,
|
||||
userId: $this->userId,
|
||||
tenantId: $this->tenantId,
|
||||
deviceInfo: $this->deviceInfo,
|
||||
location: $this->location,
|
||||
createdAt: $this->createdAt,
|
||||
lastActivityAt: $at,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si cette session correspond à la session courante.
|
||||
*/
|
||||
public function isCurrent(TokenFamilyId $currentFamilyId): bool
|
||||
{
|
||||
return $this->familyId->equals($currentFamilyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si cette session appartient à l'utilisateur donné.
|
||||
*/
|
||||
public function belongsToUser(UserId $userId): bool
|
||||
{
|
||||
return $this->userId->equals($userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstitue une session depuis le stockage.
|
||||
*
|
||||
* @internal Pour usage Infrastructure uniquement
|
||||
*/
|
||||
public static function reconstitute(
|
||||
TokenFamilyId $familyId,
|
||||
UserId $userId,
|
||||
TenantId $tenantId,
|
||||
DeviceInfo $deviceInfo,
|
||||
Location $location,
|
||||
DateTimeImmutable $createdAt,
|
||||
DateTimeImmutable $lastActivityAt,
|
||||
): self {
|
||||
return new self(
|
||||
familyId: $familyId,
|
||||
userId: $userId,
|
||||
tenantId: $tenantId,
|
||||
deviceInfo: $deviceInfo,
|
||||
location: $location,
|
||||
createdAt: $createdAt,
|
||||
lastActivityAt: $lastActivityAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Domain\Repository;
|
||||
|
||||
use App\Administration\Domain\Exception\SessionNotFoundException;
|
||||
use App\Administration\Domain\Model\RefreshToken\TokenFamilyId;
|
||||
use App\Administration\Domain\Model\Session\Session;
|
||||
use App\Administration\Domain\Model\User\UserId;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Repository pour la gestion des sessions utilisateur.
|
||||
*
|
||||
* Implémentation attendue : Redis avec TTL automatique.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
interface SessionRepository
|
||||
{
|
||||
/**
|
||||
* Sauvegarde une session.
|
||||
*
|
||||
* @param int $ttlSeconds TTL en secondes (aligné avec le refresh token)
|
||||
*/
|
||||
public function save(Session $session, int $ttlSeconds): void;
|
||||
|
||||
/**
|
||||
* Récupère une session par son family ID.
|
||||
*
|
||||
* @throws SessionNotFoundException si la session n'existe pas
|
||||
*/
|
||||
public function getByFamilyId(TokenFamilyId $familyId): Session;
|
||||
|
||||
/**
|
||||
* Recherche une session par son family ID (nullable).
|
||||
*/
|
||||
public function findByFamilyId(TokenFamilyId $familyId): ?Session;
|
||||
|
||||
/**
|
||||
* Récupère toutes les sessions d'un utilisateur.
|
||||
*
|
||||
* @return list<Session>
|
||||
*/
|
||||
public function findAllByUserId(UserId $userId): array;
|
||||
|
||||
/**
|
||||
* Supprime une session.
|
||||
*/
|
||||
public function delete(TokenFamilyId $familyId): void;
|
||||
|
||||
/**
|
||||
* Supprime toutes les sessions sauf celle spécifiée.
|
||||
*
|
||||
* @return list<TokenFamilyId> Les family IDs des sessions supprimées
|
||||
*/
|
||||
public function deleteAllExcept(UserId $userId, TokenFamilyId $exceptFamilyId): array;
|
||||
|
||||
/**
|
||||
* Met à jour le timestamp de dernière activité.
|
||||
*
|
||||
* @param int $ttlSeconds TTL restant en secondes (aligné avec le refresh token)
|
||||
*/
|
||||
public function updateActivity(TokenFamilyId $familyId, DateTimeImmutable $at, int $ttlSeconds): void;
|
||||
}
|
||||
@@ -4,27 +4,35 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Infrastructure\Api\Controller;
|
||||
|
||||
use App\Administration\Domain\Event\Deconnexion;
|
||||
use App\Administration\Domain\Model\RefreshToken\RefreshToken;
|
||||
use App\Administration\Domain\Repository\RefreshTokenRepository;
|
||||
use App\Administration\Domain\Repository\SessionRepository;
|
||||
use App\Shared\Domain\Clock;
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Logout endpoint.
|
||||
*
|
||||
* Invalidates the refresh token and deletes the cookie.
|
||||
* Invalidates the refresh token, deletes the session, and clears the cookie.
|
||||
*
|
||||
* @see Story 1.4 - User login
|
||||
* @see Story 1.6 - Session management
|
||||
*/
|
||||
final readonly class LogoutController
|
||||
{
|
||||
public function __construct(
|
||||
private RefreshTokenRepository $refreshTokenRepository,
|
||||
private SessionRepository $sessionRepository,
|
||||
private MessageBusInterface $eventBus,
|
||||
private Clock $clock,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -40,8 +48,21 @@ final readonly class LogoutController
|
||||
$refreshToken = $this->refreshTokenRepository->find($tokenId);
|
||||
|
||||
if ($refreshToken !== null) {
|
||||
// Delete the session
|
||||
$this->sessionRepository->delete($refreshToken->familyId);
|
||||
|
||||
// Invalidate the entire family (disconnects all devices)
|
||||
$this->refreshTokenRepository->invalidateFamily($refreshToken->familyId);
|
||||
|
||||
// Dispatch logout event
|
||||
$this->eventBus->dispatch(new Deconnexion(
|
||||
userId: (string) $refreshToken->userId,
|
||||
familyId: (string) $refreshToken->familyId,
|
||||
tenantId: $refreshToken->tenantId,
|
||||
ipAddress: $request->getClientIp() ?? 'unknown',
|
||||
userAgent: $request->headers->get('User-Agent', 'unknown'),
|
||||
occurredOn: $this->clock->now(),
|
||||
));
|
||||
}
|
||||
} catch (InvalidArgumentException) {
|
||||
// Malformed token, ignore
|
||||
@@ -51,15 +72,30 @@ final readonly class LogoutController
|
||||
// Create the response with cookie deletion
|
||||
$response = new JsonResponse(['message' => 'Logout successful'], Response::HTTP_OK);
|
||||
|
||||
// Delete the refresh_token cookie (same path as used during login)
|
||||
// Delete the refresh_token cookie
|
||||
// Secure flag only on HTTPS (prod), not HTTP (dev)
|
||||
$isSecure = $request->isSecure();
|
||||
|
||||
// Clear cookie at current path /api
|
||||
$response->headers->setCookie(
|
||||
Cookie::create('refresh_token')
|
||||
->withValue('')
|
||||
->withExpires(new DateTimeImmutable('-1 hour'))
|
||||
->withPath('/api')
|
||||
->withHttpOnly(true)
|
||||
->withSecure($isSecure)
|
||||
->withSameSite($isSecure ? 'strict' : 'lax'),
|
||||
);
|
||||
|
||||
// Also clear legacy cookie at /api/token (migration period)
|
||||
$response->headers->setCookie(
|
||||
Cookie::create('refresh_token')
|
||||
->withValue('')
|
||||
->withExpires(new DateTimeImmutable('-1 hour'))
|
||||
->withPath('/api/token')
|
||||
->withHttpOnly(true)
|
||||
->withSecure(true)
|
||||
->withSameSite('strict'),
|
||||
->withSecure($isSecure)
|
||||
->withSameSite($isSecure ? 'strict' : 'lax'),
|
||||
);
|
||||
|
||||
return $response;
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Infrastructure\Api\Controller;
|
||||
|
||||
use App\Administration\Domain\Event\SessionInvalidee;
|
||||
use App\Administration\Domain\Event\ToutesSessionsInvalidees;
|
||||
use App\Administration\Domain\Exception\SessionNotFoundException;
|
||||
use App\Administration\Domain\Model\RefreshToken\RefreshToken;
|
||||
use App\Administration\Domain\Model\RefreshToken\TokenFamilyId;
|
||||
use App\Administration\Domain\Model\User\UserId;
|
||||
use App\Administration\Domain\Repository\RefreshTokenRepository;
|
||||
use App\Administration\Domain\Repository\SessionRepository;
|
||||
use App\Administration\Infrastructure\Security\SecurityUser;
|
||||
use App\Shared\Domain\Clock;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
|
||||
use function array_map;
|
||||
use function count;
|
||||
|
||||
use DateTimeInterface;
|
||||
use InvalidArgumentException;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Sessions management endpoints.
|
||||
*
|
||||
* Architecture note: Events (SessionInvalidee, ToutesSessionsInvalidees) are dispatched
|
||||
* directly from this controller rather than from domain aggregates. This is a documented
|
||||
* exception to the standard DDD pattern because:
|
||||
* - Session is a read model without command/aggregate behavior
|
||||
* - The "invalidate" operation spans multiple aggregates (RefreshToken + Session)
|
||||
* - The controller orchestrates infrastructure operations, making it the natural
|
||||
* event emission point for audit trail purposes
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class SessionsController
|
||||
{
|
||||
public function __construct(
|
||||
private Security $security,
|
||||
private SessionRepository $sessionRepository,
|
||||
private RefreshTokenRepository $refreshTokenRepository,
|
||||
private MessageBusInterface $eventBus,
|
||||
private Clock $clock,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* List all active sessions for the current user.
|
||||
*/
|
||||
#[Route('/api/me/sessions', name: 'api_sessions_list', methods: ['GET'])]
|
||||
public function list(Request $request): JsonResponse
|
||||
{
|
||||
$user = $this->getSecurityUser();
|
||||
$userId = UserId::fromString($user->userId());
|
||||
$tenantId = TenantId::fromString($user->tenantId());
|
||||
|
||||
// Get the current family ID from the refresh token cookie
|
||||
$currentFamilyId = $this->getCurrentFamilyId($request, $userId);
|
||||
|
||||
$sessions = $this->sessionRepository->findAllByUserId($userId);
|
||||
|
||||
$sessionsData = [];
|
||||
foreach ($sessions as $session) {
|
||||
// Skip sessions from other tenants (defense in depth)
|
||||
if (!$session->tenantId->equals($tenantId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$isCurrent = $currentFamilyId !== null && $session->isCurrent($currentFamilyId);
|
||||
|
||||
$sessionsData[] = [
|
||||
'family_id' => (string) $session->familyId,
|
||||
'device' => $session->deviceInfo->device,
|
||||
'browser' => $session->deviceInfo->browser,
|
||||
'os' => $session->deviceInfo->os,
|
||||
'location' => $session->location->format(),
|
||||
'created_at' => $session->createdAt->format(DateTimeInterface::ATOM),
|
||||
'last_activity_at' => $session->lastActivityAt->format(DateTimeInterface::ATOM),
|
||||
'is_current' => $isCurrent,
|
||||
];
|
||||
}
|
||||
|
||||
// Sort: current session first, then by last activity (most recent first)
|
||||
usort($sessionsData, static function (array $a, array $b): int {
|
||||
if ($a['is_current'] && !$b['is_current']) {
|
||||
return -1;
|
||||
}
|
||||
if (!$a['is_current'] && $b['is_current']) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return $b['last_activity_at'] <=> $a['last_activity_at'];
|
||||
});
|
||||
|
||||
return new JsonResponse(['sessions' => $sessionsData]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a specific session.
|
||||
*/
|
||||
#[Route('/api/me/sessions/{familyId}', name: 'api_sessions_revoke', methods: ['DELETE'])]
|
||||
public function revoke(string $familyId, Request $request): JsonResponse
|
||||
{
|
||||
$user = $this->getSecurityUser();
|
||||
$userId = UserId::fromString($user->userId());
|
||||
|
||||
try {
|
||||
$targetFamilyId = TokenFamilyId::fromString($familyId);
|
||||
$session = $this->sessionRepository->getByFamilyId($targetFamilyId);
|
||||
} catch (InvalidArgumentException|SessionNotFoundException) {
|
||||
throw new NotFoundHttpException('Session not found');
|
||||
}
|
||||
|
||||
// Verify the session belongs to the user (return 404 to not leak existence)
|
||||
if (!$session->belongsToUser($userId)) {
|
||||
throw new NotFoundHttpException('Session not found');
|
||||
}
|
||||
|
||||
// Prevent revoking current session via this endpoint (use logout instead)
|
||||
$currentFamilyId = $this->getCurrentFamilyId($request, $userId);
|
||||
if ($currentFamilyId !== null && $session->isCurrent($currentFamilyId)) {
|
||||
throw new AccessDeniedHttpException('Cannot revoke current session. Use logout instead.');
|
||||
}
|
||||
|
||||
// Invalidate the token family (disconnects the device)
|
||||
$this->refreshTokenRepository->invalidateFamily($targetFamilyId);
|
||||
|
||||
// Delete the session
|
||||
$this->sessionRepository->delete($targetFamilyId);
|
||||
|
||||
// Dispatch event for audit trail
|
||||
$this->eventBus->dispatch(new SessionInvalidee(
|
||||
userId: $user->userId(),
|
||||
familyId: (string) $targetFamilyId,
|
||||
tenantId: TenantId::fromString($user->tenantId()),
|
||||
ipAddress: $request->getClientIp() ?? 'unknown',
|
||||
userAgent: $request->headers->get('User-Agent', 'unknown'),
|
||||
occurredOn: $this->clock->now(),
|
||||
));
|
||||
|
||||
return new JsonResponse(['message' => 'Session revoked'], Response::HTTP_OK);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke all sessions except the current one.
|
||||
*/
|
||||
#[Route('/api/me/sessions', name: 'api_sessions_revoke_all', methods: ['DELETE'])]
|
||||
public function revokeAll(Request $request): JsonResponse
|
||||
{
|
||||
$user = $this->getSecurityUser();
|
||||
$userId = UserId::fromString($user->userId());
|
||||
|
||||
// Get the current family ID to exclude it
|
||||
$currentFamilyId = $this->getCurrentFamilyId($request, $userId);
|
||||
|
||||
if ($currentFamilyId === null) {
|
||||
throw new AccessDeniedHttpException('Unable to identify current session');
|
||||
}
|
||||
|
||||
// Delete all sessions except current
|
||||
$deletedFamilyIds = $this->sessionRepository->deleteAllExcept($userId, $currentFamilyId);
|
||||
|
||||
// Invalidate all corresponding token families
|
||||
foreach ($deletedFamilyIds as $familyId) {
|
||||
$this->refreshTokenRepository->invalidateFamily($familyId);
|
||||
}
|
||||
|
||||
// Dispatch event for audit trail (only if sessions were actually revoked)
|
||||
if (count($deletedFamilyIds) > 0) {
|
||||
$this->eventBus->dispatch(new ToutesSessionsInvalidees(
|
||||
userId: $user->userId(),
|
||||
invalidatedFamilyIds: array_map(static fn (TokenFamilyId $id): string => (string) $id, $deletedFamilyIds),
|
||||
exceptFamilyId: (string) $currentFamilyId,
|
||||
tenantId: TenantId::fromString($user->tenantId()),
|
||||
ipAddress: $request->getClientIp() ?? 'unknown',
|
||||
userAgent: $request->headers->get('User-Agent', 'unknown'),
|
||||
occurredOn: $this->clock->now(),
|
||||
));
|
||||
}
|
||||
|
||||
return new JsonResponse([
|
||||
'message' => 'All other sessions revoked',
|
||||
'revoked_count' => count($deletedFamilyIds),
|
||||
], Response::HTTP_OK);
|
||||
}
|
||||
|
||||
private function getSecurityUser(): SecurityUser
|
||||
{
|
||||
$user = $this->security->getUser();
|
||||
|
||||
if (!$user instanceof SecurityUser) {
|
||||
throw new AccessDeniedHttpException('Authentication required');
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current session's family ID from the refresh token cookie.
|
||||
*
|
||||
* Security: Validates that the refresh token belongs to the authenticated user
|
||||
* to prevent cross-account issues in multi-tab scenarios where JWT and cookie
|
||||
* could belong to different users.
|
||||
*/
|
||||
private function getCurrentFamilyId(Request $request, UserId $authenticatedUserId): ?TokenFamilyId
|
||||
{
|
||||
$refreshTokenValue = $request->cookies->get('refresh_token');
|
||||
|
||||
if ($refreshTokenValue === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$tokenId = RefreshToken::extractIdFromTokenString($refreshTokenValue);
|
||||
$refreshToken = $this->refreshTokenRepository->find($tokenId);
|
||||
|
||||
if ($refreshToken === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Verify the refresh token belongs to the authenticated user
|
||||
// This prevents misidentification in multi-tab/account-switch scenarios
|
||||
if (!$refreshToken->userId->equals($authenticatedUserId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $refreshToken->familyId;
|
||||
} catch (InvalidArgumentException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Administration\Domain\Event\TokenReplayDetecte;
|
||||
use App\Administration\Domain\Exception\TokenAlreadyRotatedException;
|
||||
use App\Administration\Domain\Exception\TokenReplayDetectedException;
|
||||
use App\Administration\Domain\Model\RefreshToken\DeviceFingerprint;
|
||||
use App\Administration\Domain\Repository\SessionRepository;
|
||||
use App\Administration\Domain\Repository\UserRepository;
|
||||
use App\Administration\Infrastructure\Api\Resource\RefreshTokenInput;
|
||||
use App\Administration\Infrastructure\Api\Resource\RefreshTokenOutput;
|
||||
@@ -48,6 +49,7 @@ final readonly class RefreshTokenProcessor implements ProcessorInterface
|
||||
private RefreshTokenManager $refreshTokenManager,
|
||||
private JWTTokenManagerInterface $jwtManager,
|
||||
private UserRepository $userRepository,
|
||||
private SessionRepository $sessionRepository,
|
||||
private RequestStack $requestStack,
|
||||
private SecurityUserFactory $securityUserFactory,
|
||||
private TenantResolver $tenantResolver,
|
||||
@@ -106,18 +108,25 @@ final readonly class RefreshTokenProcessor implements ProcessorInterface
|
||||
|
||||
$securityUser = $this->securityUserFactory->fromDomainUser($user);
|
||||
|
||||
// Update session last activity with TTL aligned to refresh token expiry
|
||||
$now = $this->clock->now();
|
||||
$remainingTtlSeconds = $newRefreshToken->expiresAt->getTimestamp() - $now->getTimestamp();
|
||||
$this->sessionRepository->updateActivity($newRefreshToken->familyId, $now, $remainingTtlSeconds);
|
||||
|
||||
// Generate the new JWT
|
||||
$jwt = $this->jwtManager->create($securityUser);
|
||||
|
||||
// Store the cookie in request attributes for the listener
|
||||
// The RefreshTokenCookieListener will add it to the response
|
||||
// Secure flag only on HTTPS (prod), not HTTP (dev)
|
||||
$isSecure = $request->isSecure();
|
||||
$cookie = Cookie::create('refresh_token')
|
||||
->withValue($newRefreshToken->toTokenString())
|
||||
->withExpires($newRefreshToken->expiresAt)
|
||||
->withPath('/api/token')
|
||||
->withSecure(true)
|
||||
->withPath('/api')
|
||||
->withSecure($isSecure)
|
||||
->withHttpOnly(true)
|
||||
->withSameSite('strict');
|
||||
->withSameSite($isSecure ? 'strict' : 'lax');
|
||||
|
||||
$request->attributes->set('_refresh_token_cookie', $cookie);
|
||||
|
||||
@@ -156,13 +165,14 @@ final readonly class RefreshTokenProcessor implements ProcessorInterface
|
||||
$request = $this->requestStack->getCurrentRequest();
|
||||
|
||||
if ($request !== null) {
|
||||
$isSecure = $request->isSecure();
|
||||
$cookie = Cookie::create('refresh_token')
|
||||
->withValue('')
|
||||
->withExpires(new DateTimeImmutable('-1 day'))
|
||||
->withPath('/api/token')
|
||||
->withSecure(true)
|
||||
->withPath('/api')
|
||||
->withSecure($isSecure)
|
||||
->withHttpOnly(true)
|
||||
->withSameSite('strict');
|
||||
->withSameSite($isSecure ? 'strict' : 'lax');
|
||||
|
||||
$request->attributes->set('_refresh_token_cookie', $cookie);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Infrastructure\Persistence\Redis;
|
||||
|
||||
use App\Administration\Domain\Exception\SessionNotFoundException;
|
||||
use App\Administration\Domain\Model\RefreshToken\TokenFamilyId;
|
||||
use App\Administration\Domain\Model\Session\DeviceInfo;
|
||||
use App\Administration\Domain\Model\Session\Location;
|
||||
use App\Administration\Domain\Model\Session\Session;
|
||||
use App\Administration\Domain\Model\User\UserId;
|
||||
use App\Administration\Domain\Repository\SessionRepository;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
|
||||
use function count;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Psr\Cache\CacheItemPoolInterface;
|
||||
|
||||
/**
|
||||
* Redis implementation of the sessions repository.
|
||||
*
|
||||
* Storage structure:
|
||||
* - Session data: session:{family_id} → session JSON data
|
||||
* - User index: user_sessions:{user_id} → set of family_ids
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class RedisSessionRepository implements SessionRepository
|
||||
{
|
||||
private const string SESSION_PREFIX = 'session:';
|
||||
private const string USER_SESSIONS_PREFIX = 'user_sessions:';
|
||||
|
||||
/**
|
||||
* Maximum TTL for user index (8 days).
|
||||
*
|
||||
* Must be >= the longest possible session TTL to ensure
|
||||
* all sessions are properly indexed.
|
||||
*/
|
||||
private const int MAX_USER_INDEX_TTL = 691200;
|
||||
|
||||
public function __construct(
|
||||
private CacheItemPoolInterface $sessionsCache,
|
||||
) {
|
||||
}
|
||||
|
||||
public function save(Session $session, int $ttlSeconds): void
|
||||
{
|
||||
// Save the session
|
||||
$sessionItem = $this->sessionsCache->getItem(self::SESSION_PREFIX . $session->familyId);
|
||||
$sessionItem->set($this->serialize($session));
|
||||
$sessionItem->expiresAfter($ttlSeconds);
|
||||
$this->sessionsCache->save($sessionItem);
|
||||
|
||||
// Add to user index
|
||||
$userItem = $this->sessionsCache->getItem(self::USER_SESSIONS_PREFIX . $session->userId);
|
||||
|
||||
/** @var list<string> $familyIds */
|
||||
$familyIds = $userItem->isHit() ? $userItem->get() : [];
|
||||
$familyIds[] = (string) $session->familyId;
|
||||
$userItem->set(array_values(array_unique($familyIds)));
|
||||
$userItem->expiresAfter(self::MAX_USER_INDEX_TTL);
|
||||
$this->sessionsCache->save($userItem);
|
||||
}
|
||||
|
||||
public function getByFamilyId(TokenFamilyId $familyId): Session
|
||||
{
|
||||
$session = $this->findByFamilyId($familyId);
|
||||
|
||||
if ($session === null) {
|
||||
throw new SessionNotFoundException($familyId);
|
||||
}
|
||||
|
||||
return $session;
|
||||
}
|
||||
|
||||
public function findByFamilyId(TokenFamilyId $familyId): ?Session
|
||||
{
|
||||
$item = $this->sessionsCache->getItem(self::SESSION_PREFIX . $familyId);
|
||||
|
||||
if (!$item->isHit()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var array{family_id: string, user_id: string, tenant_id: string, device: string, browser: string, os: string, raw_user_agent: string, ip: string|null, country: string|null, city: string|null, created_at: string, last_activity_at: string} $data */
|
||||
$data = $item->get();
|
||||
|
||||
return $this->deserialize($data);
|
||||
}
|
||||
|
||||
public function findAllByUserId(UserId $userId): array
|
||||
{
|
||||
$userItem = $this->sessionsCache->getItem(self::USER_SESSIONS_PREFIX . $userId);
|
||||
|
||||
if (!$userItem->isHit()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @var list<string> $familyIds */
|
||||
$familyIds = $userItem->get();
|
||||
$sessions = [];
|
||||
$validFamilyIds = [];
|
||||
|
||||
foreach ($familyIds as $familyIdStr) {
|
||||
$session = $this->findByFamilyId(TokenFamilyId::fromString($familyIdStr));
|
||||
if ($session !== null) {
|
||||
$sessions[] = $session;
|
||||
$validFamilyIds[] = $familyIdStr;
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale entries from user index
|
||||
if (count($validFamilyIds) !== count($familyIds)) {
|
||||
$userItem->set($validFamilyIds);
|
||||
$userItem->expiresAfter(self::MAX_USER_INDEX_TTL);
|
||||
$this->sessionsCache->save($userItem);
|
||||
}
|
||||
|
||||
return $sessions;
|
||||
}
|
||||
|
||||
public function delete(TokenFamilyId $familyId): void
|
||||
{
|
||||
// Find session to get userId for index cleanup
|
||||
$session = $this->findByFamilyId($familyId);
|
||||
|
||||
// Delete the session
|
||||
$this->sessionsCache->deleteItem(self::SESSION_PREFIX . $familyId);
|
||||
|
||||
// Remove from user index if session existed
|
||||
if ($session !== null) {
|
||||
$this->removeFromUserIndex($session->userId, $familyId);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteAllExcept(UserId $userId, TokenFamilyId $exceptFamilyId): array
|
||||
{
|
||||
$userItem = $this->sessionsCache->getItem(self::USER_SESSIONS_PREFIX . $userId);
|
||||
|
||||
if (!$userItem->isHit()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @var list<string> $familyIds */
|
||||
$familyIds = $userItem->get();
|
||||
$deletedFamilyIds = [];
|
||||
|
||||
foreach ($familyIds as $familyIdStr) {
|
||||
$familyId = TokenFamilyId::fromString($familyIdStr);
|
||||
|
||||
if ($familyId->equals($exceptFamilyId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->sessionsCache->deleteItem(self::SESSION_PREFIX . $familyIdStr);
|
||||
$deletedFamilyIds[] = $familyId;
|
||||
}
|
||||
|
||||
// Update user index to only contain the excepted session
|
||||
$userItem->set([(string) $exceptFamilyId]);
|
||||
$userItem->expiresAfter(self::MAX_USER_INDEX_TTL);
|
||||
$this->sessionsCache->save($userItem);
|
||||
|
||||
return $deletedFamilyIds;
|
||||
}
|
||||
|
||||
public function updateActivity(TokenFamilyId $familyId, DateTimeImmutable $at, int $ttlSeconds): void
|
||||
{
|
||||
$session = $this->findByFamilyId($familyId);
|
||||
|
||||
if ($session === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$updatedSession = $session->updateActivity($at);
|
||||
|
||||
// Preserve TTL aligned with refresh token expiry
|
||||
$sessionItem = $this->sessionsCache->getItem(self::SESSION_PREFIX . $familyId);
|
||||
$sessionItem->set($this->serialize($updatedSession));
|
||||
$sessionItem->expiresAfter($ttlSeconds);
|
||||
$this->sessionsCache->save($sessionItem);
|
||||
}
|
||||
|
||||
private function removeFromUserIndex(UserId $userId, TokenFamilyId $familyId): void
|
||||
{
|
||||
$userItem = $this->sessionsCache->getItem(self::USER_SESSIONS_PREFIX . $userId);
|
||||
|
||||
if (!$userItem->isHit()) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var list<string> $familyIds */
|
||||
$familyIds = $userItem->get();
|
||||
$familyIds = array_values(array_filter(
|
||||
$familyIds,
|
||||
static fn (string $id) => $id !== (string) $familyId,
|
||||
));
|
||||
|
||||
if (count($familyIds) === 0) {
|
||||
$this->sessionsCache->deleteItem(self::USER_SESSIONS_PREFIX . $userId);
|
||||
} else {
|
||||
$userItem->set($familyIds);
|
||||
$userItem->expiresAfter(self::MAX_USER_INDEX_TTL);
|
||||
$this->sessionsCache->save($userItem);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function serialize(Session $session): array
|
||||
{
|
||||
return [
|
||||
'family_id' => (string) $session->familyId,
|
||||
'user_id' => (string) $session->userId,
|
||||
'tenant_id' => (string) $session->tenantId,
|
||||
'device' => $session->deviceInfo->device,
|
||||
'browser' => $session->deviceInfo->browser,
|
||||
'os' => $session->deviceInfo->os,
|
||||
'raw_user_agent' => $session->deviceInfo->rawUserAgent,
|
||||
'ip' => $session->location->ip,
|
||||
'country' => $session->location->country,
|
||||
'city' => $session->location->city,
|
||||
'created_at' => $session->createdAt->format(DateTimeInterface::ATOM),
|
||||
'last_activity_at' => $session->lastActivityAt->format(DateTimeInterface::ATOM),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* family_id: string,
|
||||
* user_id: string,
|
||||
* tenant_id: string,
|
||||
* device: string,
|
||||
* browser: string,
|
||||
* os: string,
|
||||
* raw_user_agent: string,
|
||||
* ip: string|null,
|
||||
* country: string|null,
|
||||
* city: string|null,
|
||||
* created_at: string,
|
||||
* last_activity_at: string
|
||||
* } $data
|
||||
*/
|
||||
private function deserialize(array $data): Session
|
||||
{
|
||||
return Session::reconstitute(
|
||||
familyId: TokenFamilyId::fromString($data['family_id']),
|
||||
userId: UserId::fromString($data['user_id']),
|
||||
tenantId: TenantId::fromString($data['tenant_id']),
|
||||
deviceInfo: DeviceInfo::reconstitute(
|
||||
device: $data['device'],
|
||||
browser: $data['browser'],
|
||||
os: $data['os'],
|
||||
rawUserAgent: $data['raw_user_agent'],
|
||||
),
|
||||
location: Location::reconstitute(
|
||||
ip: $data['ip'],
|
||||
country: $data['country'],
|
||||
city: $data['city'],
|
||||
),
|
||||
createdAt: new DateTimeImmutable($data['created_at']),
|
||||
lastActivityAt: new DateTimeImmutable($data['last_activity_at']),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Infrastructure\Security;
|
||||
|
||||
use App\Administration\Application\Port\GeoLocationService;
|
||||
use App\Administration\Application\Service\RefreshTokenManager;
|
||||
use App\Administration\Domain\Event\ConnexionReussie;
|
||||
use App\Administration\Domain\Model\RefreshToken\DeviceFingerprint;
|
||||
use App\Administration\Domain\Model\Session\DeviceInfo;
|
||||
use App\Administration\Domain\Model\Session\Session;
|
||||
use App\Administration\Domain\Model\User\UserId;
|
||||
use App\Administration\Domain\Repository\SessionRepository;
|
||||
use App\Shared\Domain\Clock;
|
||||
use App\Shared\Domain\Tenant\TenantId;
|
||||
use App\Shared\Infrastructure\RateLimit\LoginRateLimiterInterface;
|
||||
@@ -17,14 +21,17 @@ use Symfony\Component\HttpFoundation\RequestStack;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
|
||||
/**
|
||||
* Handles post-login success actions: refresh token, reset rate limit, audit.
|
||||
* Handles post-login success actions: refresh token, session, reset rate limit, audit.
|
||||
*
|
||||
* @see Story 1.4 - T5: Backend Login Endpoint
|
||||
* @see Story 1.6 - Session management
|
||||
*/
|
||||
final readonly class LoginSuccessHandler
|
||||
{
|
||||
public function __construct(
|
||||
private RefreshTokenManager $refreshTokenManager,
|
||||
private SessionRepository $sessionRepository,
|
||||
private GeoLocationService $geoLocationService,
|
||||
private LoginRateLimiterInterface $rateLimiter,
|
||||
private MessageBusInterface $eventBus,
|
||||
private Clock $clock,
|
||||
@@ -62,14 +69,35 @@ final readonly class LoginSuccessHandler
|
||||
$isMobile,
|
||||
);
|
||||
|
||||
// Create the session with metadata
|
||||
$deviceInfo = DeviceInfo::fromUserAgent($userAgent);
|
||||
$location = $this->geoLocationService->locate($ipAddress);
|
||||
$now = $this->clock->now();
|
||||
|
||||
$session = Session::create(
|
||||
familyId: $refreshToken->familyId,
|
||||
userId: $userId,
|
||||
tenantId: $tenantId,
|
||||
deviceInfo: $deviceInfo,
|
||||
location: $location,
|
||||
createdAt: $now,
|
||||
);
|
||||
|
||||
// Calculate TTL (same as refresh token)
|
||||
$ttlSeconds = $refreshToken->expiresAt->getTimestamp() - $now->getTimestamp();
|
||||
$this->sessionRepository->save($session, $ttlSeconds);
|
||||
|
||||
// Add the refresh token as HttpOnly cookie
|
||||
// Path is /api to allow session identification on /api/me/sessions endpoints
|
||||
// Secure flag only on HTTPS (prod), not HTTP (dev)
|
||||
$isSecure = $request->isSecure();
|
||||
$cookie = Cookie::create('refresh_token')
|
||||
->withValue($refreshToken->toTokenString())
|
||||
->withExpires($refreshToken->expiresAt)
|
||||
->withPath('/api/token')
|
||||
->withSecure(true)
|
||||
->withPath('/api')
|
||||
->withSecure($isSecure)
|
||||
->withHttpOnly(true)
|
||||
->withSameSite('strict');
|
||||
->withSameSite($isSecure ? 'strict' : 'lax');
|
||||
|
||||
$response->headers->setCookie($cookie);
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Administration\Infrastructure\Service;
|
||||
|
||||
use App\Administration\Application\Port\GeoLocationService;
|
||||
use App\Administration\Domain\Model\Session\Location;
|
||||
|
||||
use const FILTER_FLAG_NO_PRIV_RANGE;
|
||||
use const FILTER_FLAG_NO_RES_RANGE;
|
||||
use const FILTER_VALIDATE_IP;
|
||||
|
||||
/**
|
||||
* Null implementation of GeoLocationService.
|
||||
*
|
||||
* Always returns Location::unknown(). Use this when:
|
||||
* - No geolocation database is configured
|
||||
* - In development/test environments
|
||||
* - When privacy concerns require disabling geolocation
|
||||
*
|
||||
* For production, replace with MaxMindGeoLocationService
|
||||
* or another IP geolocation provider.
|
||||
*
|
||||
* @see Story 1.6 - Gestion des sessions
|
||||
*/
|
||||
final readonly class NullGeoLocationService implements GeoLocationService
|
||||
{
|
||||
public function locate(string $ipAddress): Location
|
||||
{
|
||||
// Store IP but don't resolve location
|
||||
// This allows for future resolution if a geo service is configured
|
||||
if ($this->isPrivateOrReserved($ipAddress)) {
|
||||
return Location::unknown();
|
||||
}
|
||||
|
||||
return Location::fromIp($ipAddress, null, null);
|
||||
}
|
||||
|
||||
private function isPrivateOrReserved(string $ip): bool
|
||||
{
|
||||
return filter_var(
|
||||
$ip,
|
||||
FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE,
|
||||
) === false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user