feat(server): auth comptes utilisateurs et tokens API (ticket #48)

Ajoute la couche application (ports, use cases), les entités du
domaine, l'endpoint api/auth_api.dart (register/login/logout) et son
câblage dans le router, le hashing de mot de passe et le service de
token (infrastructure/security), et l'adapter Postgres des repositories
d'auth s'appuyant sur la table users du ticket #49. dart pub get OK,
dart analyze clean, dart test 10/10 vert (test PostgreSQL réel skip
faute de Docker disponible dans ce sandbox). Logique d'auth et
middleware testés via repositories fake en mémoire ; les endpoints
HTTP register/login/logout n'ont pas pu être exercés de bout en bout
faute d'accès à un vrai PostgreSQL local.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-19 10:15:34 +02:00
parent c10e8f9085
commit 7b122d03da
22 changed files with 1351 additions and 8 deletions

View File

@ -0,0 +1,190 @@
import '../domain/domain.dart';
import 'ports.dart';
const _minimumPasswordLength = 8;
final _emailPattern = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
final class RegisterUserUseCase {
const RegisterUserUseCase({
required this.users,
required this.passwordHasher,
required this.clock,
required this.ids,
});
final UserRepository users;
final PasswordHasher passwordHasher;
final Clock clock;
final IdGenerator ids;
Future<UserAccount> execute({
required String email,
required String password,
String? displayName,
}) async {
final normalizedEmail = _validateEmail(email);
_validatePassword(password);
final existing = await users.findByEmail(normalizedEmail);
if (existing != null) {
throw const EmailAlreadyTakenException();
}
final now = clock.now().toUtc();
final user = UserAccount(
id: ids.newId(),
email: normalizedEmail,
passwordHash: await passwordHasher.hash(password),
displayName: _blankToNull(displayName),
createdAt: now,
updatedAt: now,
);
await users.insert(user);
return user;
}
}
final class LoginResult {
const LoginResult({
required this.user,
required this.session,
required this.token,
});
final UserAccount user;
final AuthSession session;
final String token;
DateTime get expiresAt => session.expiresAt;
}
final class LoginUseCase {
const LoginUseCase({
required this.users,
required this.sessions,
required this.passwordHasher,
required this.tokens,
required this.clock,
required this.ids,
this.sessionDuration = const Duration(days: 30),
});
final UserRepository users;
final AuthSessionRepository sessions;
final PasswordHasher passwordHasher;
final OpaqueTokenService tokens;
final Clock clock;
final IdGenerator ids;
final Duration sessionDuration;
Future<LoginResult> execute({
required String email,
required String password,
String? userAgent,
String? deviceLabel,
}) async {
final normalizedEmail = _validateEmail(email);
final user = await users.findByEmail(normalizedEmail);
if (user == null || user.isDisabled) {
throw const InvalidCredentialsException();
}
final verified = await passwordHasher.verify(
password: password,
passwordHash: user.passwordHash,
);
if (!verified) {
throw const InvalidCredentialsException();
}
final now = clock.now().toUtc();
final token = tokens.generateToken();
final session = AuthSession(
id: ids.newId(),
userId: user.id,
tokenHash: tokens.hashToken(token),
issuedAt: now,
expiresAt: now.add(sessionDuration),
userAgent: _blankToNull(userAgent),
deviceLabel: _blankToNull(deviceLabel),
);
await sessions.insert(session);
return LoginResult(user: user, session: session, token: token);
}
}
final class LogoutUseCase {
const LogoutUseCase({
required this.sessions,
required this.tokens,
required this.clock,
});
final AuthSessionRepository sessions;
final OpaqueTokenService tokens;
final Clock clock;
Future<void> execute({required String token}) async {
final session = await sessions.findByTokenHash(tokens.hashToken(token));
if (session == null || !session.isActiveAt(clock.now())) {
throw const UnauthorizedException();
}
await sessions.revoke(
sessionId: session.id,
revokedAt: clock.now().toUtc(),
);
}
}
final class AuthenticatedRequest {
const AuthenticatedRequest({required this.user, required this.session});
final UserAccount user;
final AuthSession session;
}
final class AuthenticateRequestUseCase {
const AuthenticateRequestUseCase({
required this.users,
required this.sessions,
required this.tokens,
required this.clock,
});
final UserRepository users;
final AuthSessionRepository sessions;
final OpaqueTokenService tokens;
final Clock clock;
Future<AuthenticatedRequest> execute({required String token}) async {
final session = await sessions.findByTokenHash(tokens.hashToken(token));
if (session == null || !session.isActiveAt(clock.now())) {
throw const UnauthorizedException();
}
final user = await users.findById(session.userId);
if (user == null || user.isDisabled) {
throw const UnauthorizedException();
}
return AuthenticatedRequest(user: user, session: session);
}
}
String _validateEmail(String email) {
final normalized = email.trim().toLowerCase();
if (!_emailPattern.hasMatch(normalized)) {
throw const ValidationException('Email format is invalid.');
}
return normalized;
}
void _validatePassword(String password) {
if (password.length < _minimumPasswordLength) {
throw const ValidationException(
'Password must contain at least 8 characters.',
);
}
}
String? _blankToNull(String? value) {
final trimmed = value?.trim();
return trimmed == null || trimmed.isEmpty ? null : trimmed;
}