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:
2026-02-03 10:10:40 +01:00
parent affad287f9
commit b823479658
40 changed files with 4222 additions and 42 deletions

View File

@@ -16,8 +16,40 @@ const REFRESH_RACE_RETRY_DELAY_MS = 100;
// État réactif de l'authentification
let accessToken = $state<string | null>(null);
let currentUserId = $state<string | null>(null);
let isRefreshing = $state(false);
// Callback to clear user-specific caches on logout
let onLogoutCallback: (() => void) | null = null;
/**
* Parse JWT payload to extract claims.
* Note: This does NOT validate the token - validation is done server-side.
*/
function parseJwtPayload(token: string): Record<string, unknown> | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payloadPart = parts[1];
if (!payloadPart) return null;
const decoded = atob(payloadPart.replace(/-/g, '+').replace(/_/g, '/'));
return JSON.parse(decoded) as Record<string, unknown>;
} catch {
return null;
}
}
/**
* Extract user ID from JWT token.
*/
function extractUserId(token: string): string | null {
const payload = parseJwtPayload(token);
if (!payload) return null;
// JWT 'sub' claim contains the user ID
const sub = payload['sub'];
return typeof sub === 'string' ? sub : null;
}
export interface LoginCredentials {
email: string;
password: string;
@@ -63,6 +95,7 @@ export async function login(credentials: LoginCredentials): Promise<LoginResult>
if (response.ok) {
const data = await response.json();
accessToken = data.token;
currentUserId = extractUserId(data.token);
return { success: true };
}
@@ -164,12 +197,17 @@ export async function refreshToken(retryCount = 0): Promise<boolean> {
try {
const response = await fetch(`${apiUrl}/token/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: '{}',
credentials: 'include',
});
if (response.ok) {
const data = await response.json();
accessToken = data.token;
currentUserId = extractUserId(data.token);
return true;
}
@@ -182,10 +220,12 @@ export async function refreshToken(retryCount = 0): Promise<boolean> {
// Refresh échoué - token expiré ou replay détecté
accessToken = null;
currentUserId = null;
return false;
} catch (error) {
console.error('[auth] Refresh token error:', error);
accessToken = null;
currentUserId = null;
return false;
} finally {
if (retryCount === 0) {
@@ -247,6 +287,10 @@ export async function logout(): Promise<void> {
try {
await fetch(`${apiUrl}/token/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: '{}',
credentials: 'include',
});
} catch (error) {
@@ -254,7 +298,13 @@ export async function logout(): Promise<void> {
console.warn('[auth] Logout API error (continuing with local logout):', error);
}
// Clear user-specific caches before resetting state
if (onLogoutCallback) {
onLogoutCallback();
}
accessToken = null;
currentUserId = null;
goto('/login');
}
@@ -271,3 +321,19 @@ export function isAuthenticated(): boolean {
export function getAccessToken(): string | null {
return accessToken;
}
/**
* Retourne l'ID de l'utilisateur authentifié.
* Utilisé pour scoper les caches par utilisateur.
*/
export function getCurrentUserId(): string | null {
return currentUserId;
}
/**
* Register a callback to be called on logout.
* Used to clear user-specific caches (e.g., sessions query cache).
*/
export function onLogout(callback: () => void): void {
onLogoutCallback = callback;
}

View File

@@ -0,0 +1,76 @@
import { getApiBaseUrl } from '$lib/api';
import { authenticatedFetch } from '$lib/auth';
/**
* Types pour les sessions utilisateur.
*
* @see Story 1.6 - Gestion des sessions
*/
export interface Session {
family_id: string;
device: string;
browser: string;
os: string;
location: string;
created_at: string;
last_activity_at: string;
is_current: boolean;
}
export interface SessionsResponse {
sessions: Session[];
}
export interface RevokeAllResponse {
message: string;
revoked_count: number;
}
/**
* Récupère toutes les sessions actives de l'utilisateur.
*/
export async function getSessions(): Promise<Session[]> {
const apiUrl = getApiBaseUrl();
const response = await authenticatedFetch(`${apiUrl}/me/sessions`);
if (!response.ok) {
throw new Error('Failed to fetch sessions');
}
const data: SessionsResponse = await response.json();
return data.sessions;
}
/**
* Révoque une session spécifique.
*/
export async function revokeSession(familyId: string): Promise<void> {
const apiUrl = getApiBaseUrl();
const response = await authenticatedFetch(`${apiUrl}/me/sessions/${familyId}`, {
method: 'DELETE'
});
if (!response.ok) {
if (response.status === 403) {
throw new Error('Cannot revoke current session');
}
throw new Error('Failed to revoke session');
}
}
/**
* Révoque toutes les sessions sauf la session courante.
*/
export async function revokeAllSessions(): Promise<number> {
const apiUrl = getApiBaseUrl();
const response = await authenticatedFetch(`${apiUrl}/me/sessions`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Failed to revoke all sessions');
}
const data: RevokeAllResponse = await response.json();
return data.revoked_count;
}

View File

@@ -0,0 +1,265 @@
<script lang="ts">
import type { Session } from '../api/sessions';
let { session, onRevoke }: { session: Session; onRevoke: (familyId: string) => Promise<void> } = $props();
let isRevoking = $state(false);
let showConfirm = $state(false);
type DeviceType = 'Mobile' | 'Tablet' | 'Desktop' | 'unknown';
function getDeviceType(device: string): DeviceType {
if (device === 'Mobile' || device === 'Tablet' || device === 'Desktop') {
return device;
}
return 'unknown';
}
function formatRelativeTime(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'À l\'instant';
if (diffMins < 60) return `Il y a ${diffMins} min`;
if (diffHours < 24) return `Il y a ${diffHours}h`;
if (diffDays < 7) return `Il y a ${diffDays}j`;
return date.toLocaleDateString('fr-FR', {
day: 'numeric',
month: 'short'
});
}
async function handleRevoke() {
if (!showConfirm) {
showConfirm = true;
return;
}
isRevoking = true;
try {
await onRevoke(session.family_id);
} finally {
isRevoking = false;
showConfirm = false;
}
}
function cancelRevoke() {
showConfirm = false;
}
</script>
<div class="session-card" class:is-current={session.is_current}>
<div class="session-icon">
{#if getDeviceType(session.device) === 'Mobile' || getDeviceType(session.device) === 'Tablet'}
<!-- Mobile/Tablet icon -->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="5" y="2" width="14" height="20" rx="2" ry="2"/>
<line x1="12" y1="18" x2="12.01" y2="18"/>
</svg>
{:else if getDeviceType(session.device) === 'Desktop'}
<!-- Desktop/Laptop icon -->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
<line x1="8" y1="21" x2="16" y2="21"/>
<line x1="12" y1="17" x2="12" y2="21"/>
</svg>
{:else}
<!-- Unknown device/Monitor icon -->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
<line x1="8" y1="21" x2="16" y2="21"/>
<line x1="12" y1="17" x2="12" y2="21"/>
</svg>
{/if}
</div>
<div class="session-info">
<div class="session-device">
<span class="browser">{session.browser}</span>
<span class="separator">·</span>
<span class="os">{session.os}</span>
</div>
<div class="session-meta">
<span class="location">{session.location}</span>
<span class="separator">·</span>
<span class="activity">{formatRelativeTime(session.last_activity_at)}</span>
</div>
</div>
<div class="session-actions">
{#if session.is_current}
<span class="current-badge">Session actuelle</span>
{:else if showConfirm}
<div class="confirm-actions">
<button class="btn-cancel" onclick={cancelRevoke} disabled={isRevoking}>
Annuler
</button>
<button class="btn-confirm" onclick={handleRevoke} disabled={isRevoking}>
{#if isRevoking}
<span class="spinner"></span>
{:else}
Confirmer
{/if}
</button>
</div>
{:else}
<button class="btn-revoke" onclick={handleRevoke}>
Déconnecter
</button>
{/if}
</div>
</div>
<style>
.session-card {
display: flex;
align-items: center;
gap: 16px;
padding: 16px;
background: var(--surface-elevated, #fff);
border: 1px solid var(--border-subtle, #e2e8f0);
border-radius: 12px;
transition: box-shadow 0.2s;
}
.session-card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.session-card.is-current {
border-color: var(--color-calm, hsl(142, 76%, 36%));
background: linear-gradient(135deg, hsl(142, 76%, 98%) 0%, hsl(142, 76%, 99%) 100%);
}
.session-icon {
flex-shrink: 0;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-secondary, #64748b);
background: var(--surface-muted, #f1f5f9);
border-radius: 10px;
}
.is-current .session-icon {
color: var(--color-calm, hsl(142, 76%, 36%));
background: hsl(142, 76%, 92%);
}
.session-info {
flex: 1;
min-width: 0;
}
.session-device {
display: flex;
align-items: center;
gap: 8px;
font-size: 15px;
font-weight: 500;
color: var(--text-primary, #1a1f36);
}
.session-meta {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--text-secondary, #64748b);
margin-top: 4px;
}
.separator {
color: var(--text-muted, #94a3b8);
}
.session-actions {
flex-shrink: 0;
}
.current-badge {
display: inline-flex;
align-items: center;
padding: 6px 12px;
font-size: 12px;
font-weight: 600;
color: var(--color-calm, hsl(142, 76%, 36%));
background: hsl(142, 76%, 95%);
border-radius: 16px;
}
.btn-revoke {
padding: 8px 16px;
font-size: 13px;
font-weight: 500;
color: var(--color-alert, hsl(0, 72%, 51%));
background: transparent;
border: 1px solid var(--color-alert, hsl(0, 72%, 51%));
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
}
.btn-revoke:hover {
color: #fff;
background: var(--color-alert, hsl(0, 72%, 51%));
}
.confirm-actions {
display: flex;
gap: 8px;
}
.btn-cancel {
padding: 8px 12px;
font-size: 13px;
font-weight: 500;
color: var(--text-secondary, #64748b);
background: transparent;
border: 1px solid var(--border-subtle, #e2e8f0);
border-radius: 8px;
cursor: pointer;
}
.btn-confirm {
padding: 8px 16px;
font-size: 13px;
font-weight: 500;
color: #fff;
background: var(--color-alert, hsl(0, 72%, 51%));
border: none;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
}
.btn-confirm:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.spinner {
width: 14px;
height: 14px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>

View File

@@ -0,0 +1,236 @@
<script lang="ts">
import type { Session } from '../api/sessions';
import SessionCard from './SessionCard.svelte';
let {
sessions,
onRevokeSession,
onRevokeAll
}: {
sessions: Session[];
onRevokeSession: (familyId: string) => Promise<void>;
onRevokeAll: () => Promise<void>;
} = $props();
let isRevokingAll = $state(false);
let showRevokeAllConfirm = $state(false);
const otherSessions = $derived(sessions.filter((s) => !s.is_current));
const hasOtherSessions = $derived(otherSessions.length > 0);
async function handleRevokeAll() {
if (!showRevokeAllConfirm) {
showRevokeAllConfirm = true;
return;
}
isRevokingAll = true;
try {
await onRevokeAll();
} finally {
isRevokingAll = false;
showRevokeAllConfirm = false;
}
}
function cancelRevokeAll() {
showRevokeAllConfirm = false;
}
</script>
<div class="sessions-list">
<div class="sessions-header">
<h2>Sessions actives</h2>
<p class="sessions-count">
{sessions.length} session{sessions.length > 1 ? 's' : ''} active{sessions.length > 1 ? 's' : ''}
</p>
</div>
{#if hasOtherSessions}
<div class="revoke-all-section">
{#if showRevokeAllConfirm}
<div class="revoke-all-confirm">
<p>Déconnecter {otherSessions.length} autre{otherSessions.length > 1 ? 's' : ''} session{otherSessions.length > 1 ? 's' : ''} ?</p>
<div class="confirm-buttons">
<button class="btn-cancel" onclick={cancelRevokeAll} disabled={isRevokingAll}>
Annuler
</button>
<button class="btn-confirm-all" onclick={handleRevokeAll} disabled={isRevokingAll}>
{#if isRevokingAll}
<span class="spinner"></span>
Déconnexion...
{:else}
Confirmer
{/if}
</button>
</div>
</div>
{:else}
<button class="btn-revoke-all" onclick={handleRevokeAll}>
Déconnecter toutes les autres sessions
</button>
{/if}
</div>
{/if}
<div class="sessions-grid">
{#each sessions as session (session.family_id)}
<SessionCard {session} onRevoke={onRevokeSession} />
{/each}
</div>
{#if sessions.length === 0}
<div class="empty-state">
<span class="empty-icon">
<!-- Lock/Shield icon -->
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</svg>
</span>
<p>Aucune session active</p>
</div>
{/if}
</div>
<style>
.sessions-list {
display: flex;
flex-direction: column;
gap: 20px;
}
.sessions-header {
display: flex;
justify-content: space-between;
align-items: baseline;
}
.sessions-header h2 {
font-size: 18px;
font-weight: 600;
color: var(--text-primary, #1a1f36);
margin: 0;
}
.sessions-count {
font-size: 14px;
color: var(--text-secondary, #64748b);
margin: 0;
}
.revoke-all-section {
padding: 12px 16px;
background: var(--surface-primary, #f8fafc);
border-radius: 12px;
border: 1px solid var(--border-subtle, #e2e8f0);
}
.btn-revoke-all {
width: 100%;
padding: 10px 16px;
font-size: 14px;
font-weight: 500;
color: var(--color-alert, hsl(0, 72%, 51%));
background: transparent;
border: 1px solid var(--color-alert, hsl(0, 72%, 51%));
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
}
.btn-revoke-all:hover {
color: #fff;
background: var(--color-alert, hsl(0, 72%, 51%));
}
.revoke-all-confirm {
display: flex;
flex-direction: column;
gap: 12px;
}
.revoke-all-confirm p {
margin: 0;
font-size: 14px;
font-weight: 500;
color: var(--text-primary, #1a1f36);
text-align: center;
}
.confirm-buttons {
display: flex;
gap: 12px;
justify-content: center;
}
.btn-cancel {
flex: 1;
padding: 10px 16px;
font-size: 14px;
font-weight: 500;
color: var(--text-secondary, #64748b);
background: transparent;
border: 1px solid var(--border-subtle, #e2e8f0);
border-radius: 8px;
cursor: pointer;
}
.btn-confirm-all {
flex: 1;
padding: 10px 16px;
font-size: 14px;
font-weight: 500;
color: #fff;
background: var(--color-alert, hsl(0, 72%, 51%));
border: none;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-confirm-all:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.sessions-grid {
display: flex;
flex-direction: column;
gap: 12px;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 40px 20px;
color: var(--text-muted, #94a3b8);
}
.empty-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted, #94a3b8);
}
.spinner {
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>