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:
199
server/lib/infrastructure/postgres/auth_repositories.dart
Normal file
199
server/lib/infrastructure/postgres/auth_repositories.dart
Normal file
@ -0,0 +1,199 @@
|
||||
import 'package:postgres/postgres.dart';
|
||||
|
||||
import '../../application/application.dart';
|
||||
import '../../domain/domain.dart';
|
||||
|
||||
final class PostgresUserRepository implements UserRepository {
|
||||
const PostgresUserRepository(this.connection);
|
||||
|
||||
final Connection connection;
|
||||
|
||||
@override
|
||||
Future<UserAccount?> findByEmail(String email) async {
|
||||
final result = await connection.execute(
|
||||
Sql.named('''
|
||||
SELECT id, email, password_hash, display_name, created_at, updated_at,
|
||||
disabled_at
|
||||
FROM users
|
||||
WHERE email = @email
|
||||
LIMIT 1
|
||||
'''),
|
||||
parameters: {'email': email.trim().toLowerCase()},
|
||||
);
|
||||
return result.isEmpty ? null : _userFromRow(result.single);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserAccount?> findById(String id) async {
|
||||
final result = await connection.execute(
|
||||
Sql.named('''
|
||||
SELECT id, email, password_hash, display_name, created_at, updated_at,
|
||||
disabled_at
|
||||
FROM users
|
||||
WHERE id = @id
|
||||
LIMIT 1
|
||||
'''),
|
||||
parameters: {'id': id},
|
||||
);
|
||||
return result.isEmpty ? null : _userFromRow(result.single);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> insert(UserAccount user) async {
|
||||
await connection.execute(
|
||||
Sql.named('''
|
||||
INSERT INTO users (
|
||||
id, email, password_hash, display_name, created_at, updated_at,
|
||||
disabled_at
|
||||
)
|
||||
VALUES (
|
||||
@id, @email, @password_hash, @display_name, @created_at,
|
||||
@updated_at, @disabled_at
|
||||
)
|
||||
'''),
|
||||
parameters: {
|
||||
'id': user.id,
|
||||
'email': user.email,
|
||||
'password_hash': user.passwordHash,
|
||||
'display_name': user.displayName,
|
||||
'created_at': user.createdAt,
|
||||
'updated_at': user.updatedAt,
|
||||
'disabled_at': user.disabledAt,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> updatePasswordHash({
|
||||
required String userId,
|
||||
required String passwordHash,
|
||||
required DateTime updatedAt,
|
||||
}) async {
|
||||
await connection.execute(
|
||||
Sql.named('''
|
||||
UPDATE users
|
||||
SET password_hash = @password_hash, updated_at = @updated_at
|
||||
WHERE id = @user_id
|
||||
'''),
|
||||
parameters: {
|
||||
'user_id': userId,
|
||||
'password_hash': passwordHash,
|
||||
'updated_at': updatedAt.toUtc(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class PostgresAuthSessionRepository implements AuthSessionRepository {
|
||||
const PostgresAuthSessionRepository(this.connection);
|
||||
|
||||
final Connection connection;
|
||||
|
||||
@override
|
||||
Future<void> insert(AuthSession session) async {
|
||||
await connection.execute(
|
||||
Sql.named('''
|
||||
INSERT INTO auth_sessions (
|
||||
id, user_id, token_hash, issued_at, expires_at, revoked_at,
|
||||
user_agent, device_label
|
||||
)
|
||||
VALUES (
|
||||
@id, @user_id, @token_hash, @issued_at, @expires_at, @revoked_at,
|
||||
@user_agent, @device_label
|
||||
)
|
||||
'''),
|
||||
parameters: {
|
||||
'id': session.id,
|
||||
'user_id': session.userId,
|
||||
'token_hash': session.tokenHash,
|
||||
'issued_at': session.issuedAt,
|
||||
'expires_at': session.expiresAt,
|
||||
'revoked_at': session.revokedAt,
|
||||
'user_agent': session.userAgent,
|
||||
'device_label': session.deviceLabel,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AuthSession?> findByTokenHash(String tokenHash) async {
|
||||
final result = await connection.execute(
|
||||
Sql.named('''
|
||||
SELECT id, user_id, token_hash, issued_at, expires_at, revoked_at,
|
||||
user_agent, device_label
|
||||
FROM auth_sessions
|
||||
WHERE token_hash = @token_hash
|
||||
LIMIT 1
|
||||
'''),
|
||||
parameters: {'token_hash': tokenHash},
|
||||
);
|
||||
return result.isEmpty ? null : _authSessionFromRow(result.single);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> revoke({
|
||||
required String sessionId,
|
||||
required DateTime revokedAt,
|
||||
}) async {
|
||||
await connection.execute(
|
||||
Sql.named('''
|
||||
UPDATE auth_sessions
|
||||
SET revoked_at = @revoked_at
|
||||
WHERE id = @id AND revoked_at IS NULL
|
||||
'''),
|
||||
parameters: {'id': sessionId, 'revoked_at': revokedAt.toUtc()},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
UserAccount _userFromRow(dynamic row) {
|
||||
final values = row.toColumnMap() as Map<String, Object?>;
|
||||
return UserAccount(
|
||||
id: _stringValue(values['id']),
|
||||
email: _stringValue(values['email']),
|
||||
passwordHash: _stringValue(values['password_hash']),
|
||||
displayName: values['display_name'] as String?,
|
||||
createdAt: _dateTimeValue(values['created_at']),
|
||||
updatedAt: _dateTimeValue(values['updated_at']),
|
||||
disabledAt: _nullableDateTimeValue(values['disabled_at']),
|
||||
);
|
||||
}
|
||||
|
||||
AuthSession _authSessionFromRow(dynamic row) {
|
||||
final values = row.toColumnMap() as Map<String, Object?>;
|
||||
return AuthSession(
|
||||
id: _stringValue(values['id']),
|
||||
userId: _stringValue(values['user_id']),
|
||||
tokenHash: _stringValue(values['token_hash']),
|
||||
issuedAt: _dateTimeValue(values['issued_at']),
|
||||
expiresAt: _dateTimeValue(values['expires_at']),
|
||||
revokedAt: _nullableDateTimeValue(values['revoked_at']),
|
||||
userAgent: values['user_agent'] as String?,
|
||||
deviceLabel: values['device_label'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
String _stringValue(Object? value) {
|
||||
if (value == null) {
|
||||
throw const FormatException('Expected non-null string value.');
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
DateTime _dateTimeValue(Object? value) {
|
||||
final result = _nullableDateTimeValue(value);
|
||||
if (result == null) {
|
||||
throw const FormatException('Expected non-null DateTime value.');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
DateTime? _nullableDateTimeValue(Object? value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value is DateTime) {
|
||||
return value.toUtc();
|
||||
}
|
||||
return DateTime.parse(value.toString()).toUtc();
|
||||
}
|
||||
2
server/lib/infrastructure/postgres/postgres.dart
Normal file
2
server/lib/infrastructure/postgres/postgres.dart
Normal file
@ -0,0 +1,2 @@
|
||||
export 'auth_repositories.dart';
|
||||
export 'postgres_database.dart';
|
||||
@ -1,5 +1,7 @@
|
||||
# Security infrastructure
|
||||
|
||||
Placeholder for password hashing, token signing and token verification.
|
||||
Password hashing uses PBKDF2-HMAC-SHA256 via `package:cryptography`, with a
|
||||
random per-password salt and encoded parameters in the stored hash.
|
||||
|
||||
Authentication is planned for ticket #48.
|
||||
API tokens are opaque random base64url strings generated with `Random.secure()`.
|
||||
Only the SHA-256 hash of a token is persisted.
|
||||
|
||||
88
server/lib/infrastructure/security/password_hasher.dart
Normal file
88
server/lib/infrastructure/security/password_hasher.dart
Normal file
@ -0,0 +1,88 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cryptography/cryptography.dart';
|
||||
|
||||
import '../../application/application.dart';
|
||||
import '../../domain/domain.dart';
|
||||
|
||||
final class Pbkdf2PasswordHasher implements PasswordHasher {
|
||||
Pbkdf2PasswordHasher({
|
||||
this.iterations = 210000,
|
||||
this.saltLength = 16,
|
||||
this.bits = 256,
|
||||
Random? random,
|
||||
}) : _random = random ?? Random.secure();
|
||||
|
||||
final int iterations;
|
||||
final int saltLength;
|
||||
final int bits;
|
||||
final Random _random;
|
||||
|
||||
@override
|
||||
Future<String> hash(String password) async {
|
||||
final salt = List<int>.generate(saltLength, (_) => _random.nextInt(256));
|
||||
final hash = await _derive(password, salt, iterations, bits);
|
||||
return [
|
||||
'pbkdf2_sha256',
|
||||
iterations.toString(),
|
||||
base64UrlEncode(salt),
|
||||
base64UrlEncode(hash),
|
||||
].join(r'$');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> verify({
|
||||
required String password,
|
||||
required String passwordHash,
|
||||
}) async {
|
||||
final parts = passwordHash.split(r'$');
|
||||
if (parts.length != 4 || parts[0] != 'pbkdf2_sha256') {
|
||||
throw const ValidationException('Unsupported password hash format.');
|
||||
}
|
||||
|
||||
final parsedIterations = int.tryParse(parts[1]);
|
||||
if (parsedIterations == null || parsedIterations <= 0) {
|
||||
throw const ValidationException('Invalid password hash iterations.');
|
||||
}
|
||||
|
||||
final salt = base64Url.decode(parts[2]);
|
||||
final expectedHash = base64Url.decode(parts[3]);
|
||||
final actualHash = await _derive(
|
||||
password,
|
||||
salt,
|
||||
parsedIterations,
|
||||
expectedHash.length * 8,
|
||||
);
|
||||
return _constantTimeEquals(actualHash, expectedHash);
|
||||
}
|
||||
|
||||
Future<List<int>> _derive(
|
||||
String password,
|
||||
List<int> salt,
|
||||
int iterations,
|
||||
int bits,
|
||||
) async {
|
||||
final algorithm = Pbkdf2(
|
||||
macAlgorithm: Hmac.sha256(),
|
||||
iterations: iterations,
|
||||
bits: bits,
|
||||
);
|
||||
final key = await algorithm.deriveKey(
|
||||
secretKey: SecretKey(utf8.encode(password)),
|
||||
nonce: salt,
|
||||
);
|
||||
return key.extractBytes();
|
||||
}
|
||||
}
|
||||
|
||||
bool _constantTimeEquals(List<int> left, List<int> right) {
|
||||
if (left.length != right.length) {
|
||||
return false;
|
||||
}
|
||||
var diff = 0;
|
||||
for (var index = 0; index < left.length; index++) {
|
||||
diff |= left[index] ^ right[index];
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
32
server/lib/infrastructure/security/runtime_services.dart
Normal file
32
server/lib/infrastructure/security/runtime_services.dart
Normal file
@ -0,0 +1,32 @@
|
||||
import 'dart:math';
|
||||
|
||||
import '../../application/application.dart';
|
||||
|
||||
final class SystemClock implements Clock {
|
||||
const SystemClock();
|
||||
|
||||
@override
|
||||
DateTime now() => DateTime.now().toUtc();
|
||||
}
|
||||
|
||||
final class UuidV4Generator implements IdGenerator {
|
||||
UuidV4Generator({Random? random}) : _random = random ?? Random.secure();
|
||||
|
||||
final Random _random;
|
||||
|
||||
@override
|
||||
String newId() {
|
||||
final bytes = List<int>.generate(16, (_) => _random.nextInt(256));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
final hex = bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0'));
|
||||
final value = hex.join();
|
||||
return [
|
||||
value.substring(0, 8),
|
||||
value.substring(8, 12),
|
||||
value.substring(12, 16),
|
||||
value.substring(16, 20),
|
||||
value.substring(20),
|
||||
].join('-');
|
||||
}
|
||||
}
|
||||
3
server/lib/infrastructure/security/security.dart
Normal file
3
server/lib/infrastructure/security/security.dart
Normal file
@ -0,0 +1,3 @@
|
||||
export 'password_hasher.dart';
|
||||
export 'runtime_services.dart';
|
||||
export 'token_service.dart';
|
||||
25
server/lib/infrastructure/security/token_service.dart
Normal file
25
server/lib/infrastructure/security/token_service.dart
Normal file
@ -0,0 +1,25 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
import '../../application/application.dart';
|
||||
|
||||
final class SecureOpaqueTokenService implements OpaqueTokenService {
|
||||
SecureOpaqueTokenService({this.byteLength = 32, Random? random})
|
||||
: _random = random ?? Random.secure();
|
||||
|
||||
final int byteLength;
|
||||
final Random _random;
|
||||
|
||||
@override
|
||||
String generateToken() {
|
||||
final bytes = List<int>.generate(byteLength, (_) => _random.nextInt(256));
|
||||
return base64UrlEncode(bytes).replaceAll('=', '');
|
||||
}
|
||||
|
||||
@override
|
||||
String hashToken(String token) {
|
||||
return sha256.convert(utf8.encode(token)).toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user