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:
@ -2,4 +2,5 @@
|
||||
|
||||
Server use cases, ports and API DTOs independent from Shelf and PostgreSQL.
|
||||
|
||||
Concrete adapters are wired from `bin/server.dart`.
|
||||
Authentication use cases live here and depend only on repository/security
|
||||
ports. Concrete adapters are wired from `bin/server.dart`.
|
||||
|
||||
2
server/lib/application/application.dart
Normal file
2
server/lib/application/application.dart
Normal file
@ -0,0 +1,2 @@
|
||||
export 'ports.dart';
|
||||
export 'use_cases.dart';
|
||||
43
server/lib/application/ports.dart
Normal file
43
server/lib/application/ports.dart
Normal file
@ -0,0 +1,43 @@
|
||||
import '../domain/domain.dart';
|
||||
|
||||
abstract interface class UserRepository {
|
||||
Future<UserAccount?> findByEmail(String email);
|
||||
|
||||
Future<UserAccount?> findById(String id);
|
||||
|
||||
Future<void> insert(UserAccount user);
|
||||
|
||||
Future<void> updatePasswordHash({
|
||||
required String userId,
|
||||
required String passwordHash,
|
||||
required DateTime updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
abstract interface class AuthSessionRepository {
|
||||
Future<void> insert(AuthSession session);
|
||||
|
||||
Future<AuthSession?> findByTokenHash(String tokenHash);
|
||||
|
||||
Future<void> revoke({required String sessionId, required DateTime revokedAt});
|
||||
}
|
||||
|
||||
abstract interface class PasswordHasher {
|
||||
Future<String> hash(String password);
|
||||
|
||||
Future<bool> verify({required String password, required String passwordHash});
|
||||
}
|
||||
|
||||
abstract interface class OpaqueTokenService {
|
||||
String generateToken();
|
||||
|
||||
String hashToken(String token);
|
||||
}
|
||||
|
||||
abstract interface class Clock {
|
||||
DateTime now();
|
||||
}
|
||||
|
||||
abstract interface class IdGenerator {
|
||||
String newId();
|
||||
}
|
||||
190
server/lib/application/use_cases.dart
Normal file
190
server/lib/application/use_cases.dart
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user