Files
Kifi/kifi-app/lib/features/auth/data/auth_repository.dart

115 lines
3.2 KiB
Dart

import 'package:dio/dio.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/security/crypto_service.dart';
class AuthRepository {
final Dio dio = DioClient().dio;
final CryptoService _crypto = CryptoService();
Future<void> _ensureCryptoReady() async {
if (!_crypto.isInitialized) {
await _crypto.fetchPublicKey();
}
}
Future<void> signup(String email, String password) async {
try {
await _ensureCryptoReady();
await dio.post(
'/auth/signup',
data: {
'email': _crypto.encrypt(email),
'password': _crypto.encrypt(password),
},
);
} on DioException catch (e) {
final data = e.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? e.message);
}
}
Future<Map<String, dynamic>> login(String email, String password) async {
try {
return await _attemptLogin(email, password);
} on DioException catch (e) {
if (e.response?.statusCode == 500 ||
e.response?.statusCode == 400 ||
e.response?.statusCode == 401) {
_crypto.clearKey();
try {
return await _attemptLogin(email, password);
} on DioException catch (e2) {
final data = e2.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? 'Invalid email or password');
}
}
final data = e.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? 'Invalid email or password');
}
}
Future<Map<String, dynamic>> _attemptLogin(
String email,
String password,
) async {
await _ensureCryptoReady();
final response = await dio.post(
'/auth/login',
data: {
'email': _crypto.encrypt(email),
'password': _crypto.encrypt(password),
},
);
return response.data;
}
Future<Map<String, dynamic>> verifyOtp(String email, String otp) async {
try {
final response = await dio.post(
'/auth/verify-otp',
data: {'email': email, 'otp': otp},
);
return response.data;
} on DioException catch (e) {
final data = e.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? 'Invalid OTP');
}
}
Future<void> forgotPassword(String email) async {
try {
await dio.post('/auth/forgot-password', data: {'email': email});
} on DioException catch (e) {
final data = e.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? 'Failed to send reset code');
}
}
Future<void> resetPassword(
String email,
String otp,
String newPassword,
) async {
try {
await _ensureCryptoReady();
await dio.post(
'/auth/reset-password',
data: {
'email': email,
'otp': otp,
'newPassword': _crypto.encrypt(newPassword),
},
);
} on DioException catch (e) {
final data = e.response?.data;
final errorMsg = data is Map ? data['error'] : data;
throw Exception(errorMsg ?? 'Failed to reset password');
}
}
}