38 lines
1.0 KiB
Dart
38 lines
1.0 KiB
Dart
|
|
import 'package:dio/dio.dart';
|
||
|
|
import 'package:flutter/material.dart';
|
||
|
|
import '../providers/auth_provider.dart';
|
||
|
|
|
||
|
|
class TokenInterceptor extends Interceptor {
|
||
|
|
final AuthProvider auth;
|
||
|
|
final BuildContext context;
|
||
|
|
final Dio dio;
|
||
|
|
|
||
|
|
TokenInterceptor(this.auth, this.context, this.dio);
|
||
|
|
|
||
|
|
@override
|
||
|
|
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||
|
|
if (auth.token != null) {
|
||
|
|
options.headers['Authorization'] = 'Bearer ${auth.token}';
|
||
|
|
}
|
||
|
|
handler.next(options);
|
||
|
|
}
|
||
|
|
|
||
|
|
@override
|
||
|
|
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||
|
|
if (err.response?.statusCode == 401 &&
|
||
|
|
err.response?.data['message'] == 'Token has expired') {
|
||
|
|
|
||
|
|
final refreshed = await auth.tryRefreshToken(context);
|
||
|
|
|
||
|
|
if (refreshed) {
|
||
|
|
err.requestOptions.headers['Authorization'] = 'Bearer ${auth.token}';
|
||
|
|
final newResponse = await dio.fetch(err.requestOptions);
|
||
|
|
return handler.resolve(newResponse);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
handler.next(err);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|