TokenManager class abstract

Generic token manager interface for authentication

Implement this interface to integrate with your auth system. The AuthInterceptor will use this to manage tokens.

Example Implementation:

class MyTokenManager implements TokenManager {
  final SecureStorage _storage;
  final Dio _authDio; // ✅ Dedicated Dio instance for auth

  MyTokenManager(this._storage, this._authDio);

  @override
  Future<String?> getAccessToken() async {
    return await _storage.read(key: 'access_token');
  }

  @override
  Future<String?> getRefreshToken() async {
    return await _storage.read(key: 'refresh_token');
  }

  @override
  Future<bool> refreshToken() async {
    try {
      final refreshToken = await getRefreshToken();
      if (refreshToken == null) return false;

      // ✅ Use dedicated auth Dio (without AuthInterceptor to avoid loops)
      final response = await _authDio.post(
        '/auth/refresh',
        data: {'refresh_token': refreshToken},
      );

      final newAccessToken = response.data['access_token'];
      final newRefreshToken = response.data['refresh_token'];

      await _storage.write(key: 'access_token', value: newAccessToken);
      await _storage.write(key: 'refresh_token', value: newRefreshToken);

      return true;
    } catch (e) {
      return false;
    }
  }

  @override
  Future<void> clearTokens() async {
    await _storage.delete(key: 'access_token');
    await _storage.delete(key: 'refresh_token');
  }
}

// Setup
final authDio = KeystoneNetwork.createInstance(
  baseUrl: 'https://api.example.com',
  interceptors: [
    LoggingInterceptor(), // ✅ Can still have logging
    // ❌ DON'T add AuthInterceptor here (infinite loop)
  ],
);

final tokenManager = MyTokenManager(secureStorage, authDio);

Constructors

TokenManager()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

clearTokens() Future<void>
Clear all stored tokens (logout)
getAccessToken() Future<String?>
Get the current access token
getRefreshToken() Future<String?>
Get the current refresh token
isAuthenticated() Future<bool>
Check if user is authenticated
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
refreshToken() Future<bool>
Refresh the access token using the refresh token
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited