Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@AristideVB
Copy link

Description

This PR introduces an optional shouldRefreshBeforeRequest callback to the Fresh library. The new callback allows for proactive token validation before making requests, ensuring that tokens are refreshed when necessary, reducing the risk of sending requests with expired tokens.

This PR aims to address issue #110

Key Changes

  • Added shouldRefreshBeforeRequest callback to both Fresh and FreshLink:
    • Dio: Validates the token in the onRequest interceptor.
    • GraphQL: Validates the token before forwarding the request.
  • Maintains backward compatibility by making the new callback optional.
  • Developers can now define token validation logic specific to their needs, such as checking expiration timestamps.

Usage Example

final fresh = Fresh.oAuth2(
  tokenStorage: tokenStorage,
  refreshToken: (token, client) async {
    // Refresh token logic
  },
  shouldRefresh: (response) {
    return response?.statusCode == 401;
  },
  shouldRefreshBeforeRequest: (token) async {
    final now = currentUnixTime();
    final issuedAt = await getIssuedAtFromStorage(); 
    if (token?.expiresIn != null && issuedAt != null) {
       return (issuedAt + token!.expiresIn!) < now;
    }
    return false;
  },
);

Discussion

The current name, shouldRefreshBeforeRequest, could be revised for clarity and alignment with library conventions. Open to feedback on naming and implementation.

@AristideVB AristideVB requested a review from felangel as a code owner December 4, 2024 17:24
@AristideVB
Copy link
Author

I will be adding tests once I have your feedback on the changes 🙂

@felangel
Copy link
Owner

felangel commented Dec 4, 2024

@AristideVB thanks for the PR! Thoughts on a slightly different API:

final fresh = Fresh.oAuth2(
  tokenStorage: tokenStorage,
  refreshToken: (token, client) async {
    // Refresh token logic
  },
  validateToken: (token) async {
    final now = currentUnixTime();
    final issuedAt = await getIssuedAtFromStorage(); 
    if (token?.expiresIn != null && issuedAt != null) {
       return (issuedAt + token!.expiresIn!) < now;
    }
    return false;
  },
  shouldRefresh: (response) {
    return response?.statusCode == 401;
  },
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants