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:
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;
|
||||
}
|
||||
Reference in New Issue
Block a user