auth.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from google_auth_oauthlib.flow import InstalledAppFlow
  2. from google.auth.transport.requests import Request
  3. import os
  4. import pickle
  5. import json
  6. # OAuth 2.0 scopes
  7. SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
  8. def get_token_interactive():
  9. """Perform OAuth authentication with user interaction."""
  10. creds = None
  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. try:
  20. creds.refresh(Request())
  21. print("Token refreshed successfully!")
  22. except Exception as e:
  23. print(f"Token refresh failed: {e}")
  24. creds = None
  25. if not creds:
  26. print("Starting interactive authentication...")
  27. flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", SCOPES)
  28. creds = flow.run_local_server(port=8080)
  29. # Save the credentials to a file
  30. with open(token_file, "wb") as token:
  31. pickle.dump(creds, token)
  32. print(f"Token saved to {token_file}")
  33. else:
  34. print("Token already exists and is valid.")
  35. return creds
  36. def get_token_non_interactive():
  37. """Try to use existing saved OAuth token."""
  38. token_file = "youtube_token.pickle"
  39. if os.path.exists(token_file):
  40. try:
  41. with open(token_file, "rb") as token:
  42. creds = pickle.load(token)
  43. if creds and creds.valid:
  44. print("Using existing valid OAuth token.")
  45. return creds
  46. elif creds and creds.expired and creds.refresh_token:
  47. try:
  48. creds.refresh(Request())
  49. print("OAuth token refreshed successfully!")
  50. # Save refreshed token
  51. with open(token_file, "wb") as token:
  52. pickle.dump(creds, token)
  53. return creds
  54. except Exception as e:
  55. print(f"OAuth token refresh failed: {e}")
  56. except Exception as e:
  57. print(f"Error loading saved OAuth token: {e}")
  58. print("No valid OAuth token found.")
  59. print("Run: python3 auth.py --interactive to authenticate.")
  60. return None
  61. print("No valid non-interactive OAuth token available.")
  62. print("Run: python3 auth.py --interactive to authenticate.")
  63. return None
  64. def get_token():
  65. """Main authentication function - tries non-interactive first."""
  66. return get_token_non_interactive()
  67. if __name__ == "__main__":
  68. import sys
  69. if "--interactive" in sys.argv:
  70. creds = get_token_interactive()
  71. else:
  72. creds = get_token_non_interactive()
  73. if not creds:
  74. print("\nTo authenticate interactively, run: python3 auth.py --interactive")
  75. if creds:
  76. print("Authentication successful!")
  77. else:
  78. print("Authentication failed!")
  79. sys.exit(1)