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