Language Changes
This commit is contained in:
56
lib/api/interceptors/auth_interceptor.dart
Normal file
56
lib/api/interceptors/auth_interceptor.dart
Normal file
@@ -0,0 +1,56 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../data/repositories/auth_repository.dart';
|
||||
|
||||
class AuthInterceptor extends Interceptor {
|
||||
final AuthRepository _authRepository;
|
||||
final Dio _dio;
|
||||
|
||||
AuthInterceptor(this._authRepository, this._dio);
|
||||
|
||||
@override
|
||||
Future<void> onRequest(
|
||||
RequestOptions options,
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
// Skip auth header for login and refresh endpoints
|
||||
if (options.path.contains('/login') ||
|
||||
options.path.contains('/auth/refresh')) {
|
||||
return handler.next(options);
|
||||
}
|
||||
|
||||
// Get token and add to request
|
||||
final token = await _authRepository.getAccessToken();
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
|
||||
return handler.next(options);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onError(
|
||||
DioException err,
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
// Handle 401 errors by refreshing token and retrying
|
||||
if (err.response?.statusCode == 401) {
|
||||
// On 401, try to get a new token
|
||||
final token = await _authRepository.getAccessToken();
|
||||
|
||||
if (token != null) {
|
||||
// If we have a new token, retry the request
|
||||
final opts = err.requestOptions;
|
||||
opts.headers['Authorization'] = 'Bearer $token';
|
||||
|
||||
try {
|
||||
final response = await _dio.fetch(opts);
|
||||
return handler.resolve(response);
|
||||
} on DioException catch (e) {
|
||||
return handler.next(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return handler.next(err);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user