Skip to content

Instantly share code, notes, and snippets.

@evanpurkhiser
Created September 21, 2018 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanpurkhiser/23bd138ba1f8ca7bb8a9317812228a0a to your computer and use it in GitHub Desktop.
Save evanpurkhiser/23bd138ba1f8ca7bb8a9317812228a0a to your computer and use it in GitHub Desktop.
class ClientTokenRefresh(object):
"""
ClientTokenRefresh provides functionality to refresh Identity and
Integration access tokens for integration API clients.
Not all integrations will need this as some use non-expiring tokens.
"""
@classmethod
def check_auth(cls, model, force_refresh=False, refresh_strategy=None, **kwargs):
"""
Check auth provides a generic yet configurable way to refresh oauth2
style authentication tokens.
Depending on the model passed different strategies will be used to
refresh the token.
- Identity
When an Identity model is provided, the token will be refreshed using
the identity providers `refresh_identity` method. Updating and
returning the identity model.
- Integration
When an Integration model is provided, the token will be refreshed
using the identity provider associated to the intergrations
`refresh_oauth_data` method the token, however the access token
will be persisted on the intergration model.
If the token should not be refreshed using the identity providers `refresh_oauth_data`
capabilities, a custom refresh strategy can be provided.
By default this wiill check the ``exipred_at`` key, which is expected
to be a unix timestamp, with the current time. If you wish to force
access token refreshing (or require a different strategy for comparing
expires_at) you may pass ``force_refresh=True``.
"""
if isinstance(model, Identity):
oauth_data = model.data
strategy = cls.strategy_identity_refresh
elif isinstance(model, Integration):
oauth_data = model.metadata
strategy = cls.strategy_integration_oauth_refresh
# Use a default strategy for the provided model if no custom strategy
# is provided
if refresh_strategy is None:
refresh_strategy = strategy
expires_at = oauth_data.get('expires_at')
# If we have no expires_at time then we should immedaitely try and refresh
# the token. This is likely due to integrations such as slack that
# previosuly did *not* have expiring tokens, or integrations that
# previously set a 'expires' isntead of 'expires_at' key.
if expires_at is None:
force_refresh = True
if force_refresh or int(expires_at) <= int(time()):
return refresh_strategy(model, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment