Created
September 5, 2024 11:41
-
-
Save GGontijo/0d411dc68f0ed11778d55ebe7bc0d7ef to your computer and use it in GitHub Desktop.
Oauth2 Token Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from contextlib import contextmanager | |
| import time | |
| from requests_oauthlib import OAuth2Session | |
| from oauthlib.oauth2 import BackendApplicationClient | |
| class TokenManager: | |
| def __init__(self, client_id, client_secret, token_url, scopes): | |
| self.client_id = client_id | |
| self.client_secret = client_secret | |
| self.token_url = token_url | |
| self.scopes = scopes | |
| self.token = None | |
| self.expires_at = None | |
| self.oauth = OAuth2Session(client=BackendApplicationClient(client_id=self.client_id)) | |
| def fetch_token(self): | |
| self.token = self.oauth.fetch_token(token_url=self.token_url, client_id=self.client_id, client_secret=self.client_secret, scope=self.scopes, headers={'Accept':'application/json'}) | |
| self.expires_at = self.token['expires_at'] | |
| return self.token | |
| def is_token_expired(self): | |
| return time.time() >= self.expires_at | |
| @contextmanager | |
| def get_token(self): | |
| if not self.token or self.is_token_expired(): | |
| self.fetch_token() | |
| try: | |
| yield self.token['access_token'] | |
| finally: | |
| # Optional: Clean up if needed | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment