Files
Finlytic/FinlyticApp/lib/features/auth/repositories/auth_repository.dart
T

76 lines
2.4 KiB
Dart

import 'package:finlytic_app/core/network/api_client.dart';
import 'package:finlytic_app/core/services/secure_storage_service.dart';
import 'package:finlytic_app/features/auth/models/user_model.dart';
class AuthRepository {
final ApiClient apiClient;
final SecureStorageService storageService;
AuthRepository({
required this.apiClient,
required this.storageService,
});
Future<UserModel?> checkAuthStatus() async {
final token = await storageService.getToken();
if (token == null || token.isEmpty) {
return null;
}
try {
final response = await apiClient.get('/api/v1/user/me');
if (response.statusCode == 200 && response.data != null) {
return UserModel.fromJson(response.data, token: token);
} else {
await storageService.clearAll();
return null;
}
} catch (_) {
await storageService.clearAll();
return null;
}
}
Future<UserModel> login(String email, String password) async {
final res = await apiClient.post('/api/v1/auth/login', data: {
'email': email,
'password': password,
});
if (res.statusCode == 200 && res.data != null) {
final token = res.data['token']?.toString() ?? '';
if (res.data['requiresPasswordChange'] == true) {
// The backend already issues a valid JWT even when a password change is required, so it must be
// persisted here: the subsequent change-initial-password call is an [Authorize]-protected endpoint
// and has no other way to authenticate itself.
await storageService.saveToken(token);
throw RequiresPasswordChangeException(res.data['userId']?.toString() ?? '');
}
final user = UserModel.fromJson(res.data, token: token);
await storageService.saveToken(token);
await storageService.saveUserEmail(user.email);
return user;
} else {
throw Exception('Ungültige Anmeldedaten');
}
}
Future<bool> changeInitialPassword(String userId, String newPassword) async {
final res = await apiClient.post('/api/v1/auth/change-initial-password', data: {
'userId': userId,
'newPassword': newPassword,
});
return res.statusCode == 200;
}
Future<void> logout() async {
await storageService.clearAll();
}
}
class RequiresPasswordChangeException implements Exception {
final String userId;
RequiresPasswordChangeException(this.userId);
}