checkpoint
This commit is contained in:
@@ -170,6 +170,46 @@ class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if token expires within the specified duration (default: 5 minutes)
|
||||
bool isTokenExpiringSoon(String? token, {Duration threshold = const Duration(minutes: 5)}) {
|
||||
if (token == null || token.isEmpty) return true;
|
||||
try {
|
||||
final decodedToken = JwtDecoder.decode(token);
|
||||
final exp = decodedToken['exp'] as int?;
|
||||
if (exp == null) return true;
|
||||
|
||||
final expirationTime = DateTime.fromMillisecondsSinceEpoch(exp * 1000);
|
||||
final now = DateTime.now();
|
||||
final timeUntilExpiration = expirationTime.difference(now);
|
||||
|
||||
return timeUntilExpiration <= threshold;
|
||||
} catch (e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Proactively refresh token if it's expiring soon
|
||||
/// Returns the current valid token or a newly refreshed token
|
||||
Future<String?> ensureValidToken() async {
|
||||
final currentToken = await getToken();
|
||||
|
||||
// If no token, return null
|
||||
if (currentToken == null) return null;
|
||||
|
||||
// If token is still valid and not expiring soon, return it
|
||||
if (!isTokenExpiringSoon(currentToken)) {
|
||||
return currentToken;
|
||||
}
|
||||
|
||||
// Token is expiring soon, refresh it
|
||||
final refreshResult = await refreshAccessToken();
|
||||
return refreshResult.when(
|
||||
success: (newToken) => newToken,
|
||||
onError: (error) => null,
|
||||
cancelled: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
UserProfile? decodeToken(String token) {
|
||||
try {
|
||||
final decodedToken = JwtDecoder.decode(token);
|
||||
|
||||
Reference in New Issue
Block a user