-
Notifications
You must be signed in to change notification settings - Fork 1
/
token_manager.py
56 lines (42 loc) · 1.88 KB
/
token_manager.py
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
import os
import json
import httpx
from cryptography.fernet import Fernet
class SecureTokenStorage:
def __init__(self, file_path, key=None):
self.file_path = file_path
self.key = key or Fernet.generate_key()
self.cipher_suite = Fernet(self.key)
def store_tokens(self, access_token, refresh_token):
data = {"access_token": access_token, "refresh_token": refresh_token}
encrypted_data = self.cipher_suite.encrypt(json.dumps(data).encode())
with open(self.file_path, "wb") as file:
file.write(encrypted_data)
def retrieve_tokens(self):
if not os.path.exists(self.file_path):
return None, None
with open(self.file_path, "rb") as file:
encrypted_data = file.read()
data = json.loads(self.cipher_suite.decrypt(encrypted_data).decode())
return data.get("access_token"), data.get("refresh_token")
class TokenManager:
def __init__(self, client_id, client_secret, port, scopes, token_storage):
self.client_id = client_id
self.client_secret = client_secret
self.port = port
self.scopes = scopes
self.token_storage = token_storage
async def generate_token(self):
access_token, refresh_token = self.token_storage.retrieve_tokens()
if not access_token:
access_token, refresh_token = await self._generate_new_token()
return access_token, refresh_token
async def _generate_new_token(self):
# Implement token generation logic here, similar to your existing generate_token function.
...
async def refresh_tokens(self):
access_token, refresh_token = await refresh_tokens(
self.client_id, self.client_secret, self.token_storage.retrieve_refresh_token()
)
self.token_storage.store_tokens(access_token, refresh_token)
return access_token, refresh_token