auth.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from google_auth_oauthlib.flow import InstalledAppFlow
  2. from google.auth.transport.requests import Request
  3. import os
  4. import pickle
  5. # OAuth 2.0 scopes
  6. SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
  7. def get_token():
  8. """Perform OAuth authentication and save the token."""
  9. creds = None
  10. # The token file to save credentials
  11. token_file = "youtube_token.pickle"
  12. # Check if token file exists
  13. if os.path.exists(token_file):
  14. with open(token_file, "rb") as token:
  15. creds = pickle.load(token)
  16. # If no valid credentials, authenticate user
  17. if not creds or not creds.valid:
  18. if creds and creds.expired and creds.refresh_token:
  19. creds.refresh(Request())
  20. else:
  21. flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", SCOPES)
  22. creds = flow.run_local_server(port=0)
  23. # Save the credentials to a file
  24. with open(token_file, "wb") as token:
  25. pickle.dump(creds, token)
  26. print(f"Token saved to {token_file}")
  27. else:
  28. print("Token already exists and is valid.")
  29. if __name__ == "__main__":
  30. get_token()