Files
ai-contract-platform/mobile/lib/features/auth/application/auth_controller.dart
T

70 lines
1.9 KiB
Dart

import 'package:flutter/material.dart';
import '../../../shared/network/api_client.dart';
import '../../../shared/storage/session_store.dart';
import '../domain/auth_session.dart';
class AuthController {
AuthController({ApiClient? apiClient})
: _apiClient = apiClient ?? const ApiClient();
final ApiClient _apiClient;
final ValueNotifier<bool> isLoading = ValueNotifier<bool>(false);
final ValueNotifier<String?> errorMessage = ValueNotifier<String?>(null);
Future<void> login(
{required String account, required String password}) async {
final normalizedAccount = _normalizeLoginAccount(account);
isLoading.value = true;
errorMessage.value = null;
try {
final session = await _apiClient.login(
account: normalizedAccount,
password: password,
);
final currentUser =
await _apiClient.fetchCurrentUser(session.accessToken);
await SessionStore.save(_mergeSession(session, currentUser));
} on ApiException catch (error) {
errorMessage.value = error.message;
rethrow;
} catch (_) {
errorMessage.value = '登录失败,请稍后重试';
rethrow;
} finally {
isLoading.value = false;
}
}
Future<void> logout() async {
await SessionStore.clear();
errorMessage.value = null;
}
AuthSession _mergeSession(AuthSession session, AuthSession currentUser) {
return session.copyWith(
userId: currentUser.userId,
tenantId: currentUser.tenantId,
username: currentUser.username,
userDisplayName: currentUser.userDisplayName,
role: currentUser.role,
status: currentUser.status,
);
}
}
String _normalizeLoginAccount(String value) {
final trimmed = value.trim();
if (trimmed.isEmpty) {
return trimmed;
}
return trimmed
.replaceAll('\uFF20', '@')
.replaceAll('\uFE6B', '@')
.replaceAll('\u3002', '.')
.replaceAll('\uFF0E', '.')
.replaceAll('\uFF61', '.');
}