Переглянути джерело

Added oauth token generation

Murad Jabir 1 рік тому
батько
коміт
5aa963c4e8
1 змінених файлів з 36 додано та 0 видалено
  1. 36 0
      auth.py

+ 36 - 0
auth.py

@@ -0,0 +1,36 @@
+from google_auth_oauthlib.flow import InstalledAppFlow
+from google.auth.transport.requests import Request
+import os
+import pickle
+
+# OAuth 2.0 scopes
+SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
+
+def get_token():
+    """Perform OAuth authentication and save the token."""
+    creds = None
+    # The token file to save credentials
+    token_file = "youtube_token.pickle"
+
+    # Check if token file exists
+    if os.path.exists(token_file):
+        with open(token_file, "rb") as token:
+            creds = pickle.load(token)
+
+    # If no valid credentials, authenticate user
+    if not creds or not creds.valid:
+        if creds and creds.expired and creds.refresh_token:
+            creds.refresh(Request())
+        else:
+            flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", SCOPES)
+            creds = flow.run_local_server(port=0)
+        # Save the credentials to a file
+        with open(token_file, "wb") as token:
+            pickle.dump(creds, token)
+        print(f"Token saved to {token_file}")
+    else:
+        print("Token already exists and is valid.")
+
+if __name__ == "__main__":
+    get_token()
+