-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
68 lines (59 loc) · 2.32 KB
/
Copy pathauth.py
File metadata and controls
68 lines (59 loc) · 2.32 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
66
67
68
import os, json, requests
from dotenv import load_dotenv
TOKEN_FILE = "tokens.json"
#This auth module is used to get the access tokens for the call that require oauth. For this to work the please run the oauth.py file and grant permission
load_dotenv()
BASE_URL = "https://www.googleapis.com/youtube/v3"
print("Running auth handler")
def save_tokens(tokens):
with open(TOKEN_FILE, "w") as f:
json.dump(tokens, f)
def load_tokens():
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, "r") as f:
return json.load(f)
return None
def refresh_access_token(refresh_token):
print("Refreshing token")
url = "https://oauth2.googleapis.com/token"
print("refresh dbug ",os.getenv("GOOGLE_CLIENT_ID"))
data = {
"client_id": os.getenv("GOOGLE_CLIENT_ID"),
"client_secret": os.getenv("GOOGLE_CLIENT_SECRET"),
"refresh_token": refresh_token,
"grant_type": "refresh_token",
}
r = requests.post(url, data=data)
tokens = r.json()
if "error" in tokens:
raise RuntimeError(f"Failed to refresh token: {tokens}")
tokens["refresh_token"] = refresh_token # keep old refresh token
save_tokens(tokens)
return tokens
def validate_token(access_token: str) -> bool:
"""Make a lightweight API call to check if token is still valid."""
url = f"{BASE_URL}/channels"
params = {"part": "id", "mine": "true"}
headers = {"Authorization": f"Bearer {access_token}"}
resp = requests.get(url, params=params, headers=headers)
if resp.status_code == 401: # Unauthorized
return False
return True
def get_access_token():
tokens = load_tokens()
print("Getting the access token")
print(tokens)
if not tokens:
raise RuntimeError("No tokens found. Please authenticate first.")
if "access_token" not in tokens:
raise RuntimeError("Token file invalid.")
access_token = tokens["access_token"]
if not validate_token(access_token):
print("Access token invalid or expired, refreshing...")
if "refresh_token" in tokens:
tokens = refresh_access_token(tokens["refresh_token"])
access_token = tokens["access_token"]
else:
raise RuntimeError("No refresh token found. Re-authentication required.")
return tokens["access_token"]
print(get_access_token())