forked from zulip/python-zulip-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-google-credentials
executable file
·68 lines (53 loc) · 2.27 KB
/
get-google-credentials
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
62
63
64
65
66
67
68
#!/usr/bin/env python3
import argparse
import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
flags = argparse.ArgumentParser(description="Google Calendar Bot")
flags.add_argument(
"--noauth_local_webserver",
action="store_true",
help="Run OAuth flow in console instead of opening a web browser.",
)
args = flags.parse_args()
# If modifying these scopes, delete your previously saved credentials
# at zulip/bots/gcal/
# NOTE: When adding more scopes, add them after the previous one in the same field, with a space
# seperating them.
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
# This file contains the information that google uses to figure out which application is requesting
# this client's data.
CLIENT_SECRET_FILE = "client_secret.json" # noqa: S105
APPLICATION_NAME = "Zulip Calendar Bot"
HOME_DIR = os.path.expanduser("~")
CREDENTIALS_PATH = os.path.join(HOME_DIR, "google-credentials.json")
def get_credentials() -> Credentials:
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
creds = None
# Check if the credentials file exists
if os.path.exists(CREDENTIALS_PATH):
creds = Credentials.from_authorized_user_file(CREDENTIALS_PATH, SCOPES)
# If there are no valid credentials, initiate the OAuth flow
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(
os.path.join(HOME_DIR, CLIENT_SECRET_FILE), SCOPES
)
if args.noauth_local_webserver:
creds = flow.run_console()
else:
creds = flow.run_local_server(port=0)
# Save the credentials for future use
with open(CREDENTIALS_PATH, "w") as token_file:
token_file.write(creds.to_json())
print("Storing credentials to " + CREDENTIALS_PATH)
return creds # Return the obtained credentials
get_credentials()