Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
1.5 kB
6
Indexable
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:s_mmobiileapp/auth/custom_auth/auth_util.dart';
import 'package:backend/api_requests/api_interceptor.dart';
import 'package:backend/api_requests/api_calls.dart';

class RefreshTokenInterceptor extends FFApiInterceptor {
  Future<bool> _hasInternetConnection() async {
    return (await Connectivity().checkConnectivity()) != ConnectivityResult.none;
  }

  Future<void> _refreshTokenIfNecessary() async {
    final tokenExpiration = authManager.tokenExpiration;
    if (tokenExpiration != null) {
      final needsRefresh = tokenExpiration.subtract(Duration(days: 1)).isBefore(getCurrentTimestamp());
      if (needsRefresh && !await authManager.refreshToken()) {
        throw Exception('Error al refrescar el token');
      }
    }
  }

  @override
  Future<ApiCallOptions> onRequest({required ApiCallOptions options}) async {
    if (!await _hasInternetConnection()) {
      throw Exception('No hay conexión a Internet');
    }

    await _refreshTokenIfNecessary();
    return options;
  }

  @override
  Future<ApiCallResponse> onResponse({
    required ApiCallResponse response,
    required Future<ApiCallResponse> Function() retryFn,
  }) async {
    if (response.statusCode == 401) {
      if (await authManager.refreshToken()) {
        return retryFn();
      } else {
        throw Exception('No autorizado y no se pudo refrescar el token');
      }
    }
    return response;
  }
}
Leave a Comment