bytelyst-devops-tools/scripts/hermes-google-drive-oauth-login.py

39 lines
1.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Create a Google Drive OAuth user token for personal Drive uploads."""
from __future__ import annotations
from pathlib import Path
import sys
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_SECRET = Path("/root/.config/hermes-google-drive/oauth-client.json")
TOKEN_FILE = Path("/root/.config/hermes-google-drive/user-token.json")
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
def main() -> int:
if not CLIENT_SECRET.exists():
print(f"Missing OAuth client secret: {CLIENT_SECRET}", file=sys.stderr)
print("Create a Google OAuth client of type Desktop app and save its JSON there.", file=sys.stderr)
return 1
flow = InstalledAppFlow.from_client_secrets_file(str(CLIENT_SECRET), SCOPES)
flow.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline")
print("Open this URL in your browser, approve access, then paste the code here:")
print(auth_url)
code = input("Code: ").strip()
flow.fetch_token(code=code)
creds = flow.credentials
TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
TOKEN_FILE.write_text(creds.to_json())
TOKEN_FILE.chmod(0o600)
print(f"OAuth user token saved: {TOKEN_FILE}")
return 0
if __name__ == "__main__":
raise SystemExit(main())