|
| 1 | +""" |
| 2 | +Token class for authentication tokens with expiry handling. |
| 3 | +""" |
| 4 | + |
| 5 | +from datetime import datetime, timezone, timedelta |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | + |
| 9 | +class Token: |
| 10 | + """ |
| 11 | + Represents an OAuth token with expiry information. |
| 12 | +
|
| 13 | + This class handles token state including expiry calculation. |
| 14 | + """ |
| 15 | + |
| 16 | + # Minimum time buffer before expiry to consider a token still valid (in seconds) |
| 17 | + MIN_VALIDITY_BUFFER = 10 |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + access_token: str, |
| 22 | + token_type: str, |
| 23 | + refresh_token: str = "", |
| 24 | + expiry: Optional[datetime] = None, |
| 25 | + ): |
| 26 | + """ |
| 27 | + Initialize a Token object. |
| 28 | +
|
| 29 | + Args: |
| 30 | + access_token: The access token string |
| 31 | + token_type: The token type (usually "Bearer") |
| 32 | + refresh_token: Optional refresh token |
| 33 | + expiry: Token expiry datetime, must be provided |
| 34 | +
|
| 35 | + Raises: |
| 36 | + ValueError: If no expiry is provided |
| 37 | + """ |
| 38 | + self.access_token = access_token |
| 39 | + self.token_type = token_type |
| 40 | + self.refresh_token = refresh_token |
| 41 | + |
| 42 | + # Ensure we have an expiry time |
| 43 | + if expiry is None: |
| 44 | + raise ValueError("Token expiry must be provided") |
| 45 | + |
| 46 | + # Ensure expiry is timezone-aware |
| 47 | + if expiry.tzinfo is None: |
| 48 | + # Convert naive datetime to aware datetime |
| 49 | + self.expiry = expiry.replace(tzinfo=timezone.utc) |
| 50 | + else: |
| 51 | + self.expiry = expiry |
| 52 | + |
| 53 | + def is_valid(self) -> bool: |
| 54 | + """ |
| 55 | + Check if the token is valid (has at least MIN_VALIDITY_BUFFER seconds before expiry). |
| 56 | +
|
| 57 | + Returns: |
| 58 | + bool: True if the token is valid, False otherwise |
| 59 | + """ |
| 60 | + buffer = timedelta(seconds=self.MIN_VALIDITY_BUFFER) |
| 61 | + return datetime.now(tz=timezone.utc) + buffer < self.expiry |
| 62 | + |
| 63 | + def __str__(self) -> str: |
| 64 | + """Return the token as a string in the format used for Authorization headers.""" |
| 65 | + return f"{self.token_type} {self.access_token}" |
0 commit comments