kmobile/lib/api/services/auth_service.dart

54 lines
1.4 KiB
Dart

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../../features/auth/models/auth_token.dart';
import '../../features/auth/models/auth_credentials.dart';
import '../../core/errors/exceptions.dart';
class AuthService {
final Dio _dio;
AuthService(this._dio);
Future<AuthToken> login(AuthCredentials credentials) async {
try {
final response = await _dio.post(
'/login',
data: credentials.toJson(),
);
if (response.statusCode == 200) {
return AuthToken.fromJson(response.data);
} else {
throw AuthException('Login failed');
}
} on DioException catch (e) {
if (kDebugMode) {
print(e.toString());
}
if (e.response?.statusCode == 401) {
throw AuthException('Invalid credentials');
}
throw NetworkException('Network error during login');
} catch (e) {
throw UnexpectedException('Unexpected error during login: ${e.toString()}');
}
}
Future<AuthToken> refreshToken(String refreshToken) async {
try {
final response = await _dio.post(
'/auth/refresh',
data: {'refresh_token': refreshToken},
);
if (response.statusCode == 200) {
return AuthToken.fromJson(response.data);
} else {
throw AuthException('Token refresh failed');
}
} catch (e) {
throw AuthException('Failed to refresh token: ${e.toString()}');
}
}
}