File size: 1,947 Bytes
0d37119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CLI script to authenticate Google account (manual code paste)."""

import json
from pathlib import Path

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow

SCOPES = [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.googleapis.com/auth/documents.readonly",
    "https://www.googleapis.com/auth/drive.metadata.readonly",
]

CLIENT_SECRET_PATH = Path(__file__).parent / "client_secret.json"
TOKEN_PATH = Path(__file__).parent / "token.json"

REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"


def main():
    with open(CLIENT_SECRET_PATH) as f:
        client_config = json.load(f)

    if "web" in client_config:
        web = client_config["web"]
        config = {
            "installed": {
                "client_id": web["client_id"],
                "client_secret": web["client_secret"],
                "auth_uri": web["auth_uri"],
                "token_uri": web["token_uri"],
                "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"],
            }
        }
    else:
        config = client_config

    flow = Flow.from_client_config(config, scopes=SCOPES, redirect_uri="http://localhost:8091/")

    auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent")

    print("\n=== Google OAuth ===")
    print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")
    print("After granting permissions, you'll be redirected to localhost.")
    print("Copy the FULL URL from your browser address bar and paste it here.\n")

    redirect_url = input("Paste the redirect URL here: ").strip()

    flow.fetch_token(authorization_response=redirect_url)
    creds = flow.credentials

    TOKEN_PATH.write_text(creds.to_json())
    print(f"\nToken saved to {TOKEN_PATH}")
    print("You're authenticated! All Google API tools are now live.")


if __name__ == "__main__":
    main()