88 lines
2.7 KiB
Dart
88 lines
2.7 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) {
|
|
if (res.data['requiresPasswordChange'] == true) {
|
|
throw RequiresPasswordChangeException(res.data['userId']?.toString() ?? '');
|
|
}
|
|
|
|
final token = res.data['token']?.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<UserModel> register(String email, String password, String fullName) async {
|
|
final res = await apiClient.post('/api/v1/auth/register', data: {
|
|
'email': email,
|
|
'password': password,
|
|
'fullName': fullName,
|
|
});
|
|
if (res.statusCode == 200 && res.data != null) {
|
|
final token = res.data['token']?.toString() ?? '';
|
|
final user = UserModel.fromJson(res.data, token: token);
|
|
await storageService.saveToken(token);
|
|
await storageService.saveUserEmail(user.email);
|
|
return user;
|
|
} else {
|
|
throw Exception('Registrierung fehlgeschlagen');
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
|