forked from marcboeker/gmail-to-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
40 lines (30 loc) · 1.28 KB
/
auth.py
File metadata and controls
40 lines (30 loc) · 1.28 KB
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
import json
import os
import google.oauth2
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
OAUTH2_CREDENTIALS = "credentials.json"
def get_credentials(data_dir: str) -> google.oauth2.credentials.Credentials:
"""
Retrieves the authentication credentials for the specified data_dir by either loading
it from the <data_dir>/credentials.json file or by running the authentication flow.
Args:
data_dir (str): The path where to store data.
Returns:
google.oauth2.credentials.Credentials: The authentication credentials.
"""
if not os.path.exists(OAUTH2_CREDENTIALS):
raise ValueError("credentials.json not found")
flow = InstalledAppFlow.from_client_secrets_file(OAUTH2_CREDENTIALS, SCOPES)
credentials_file = f"{data_dir}/credentials.json"
if not os.path.exists(credentials_file):
credentials = flow.run_local_server(port=0)
with open(credentials_file, "w") as f:
f.write(credentials.to_json())
else:
with open(credentials_file, "r") as f:
credentials_dict = json.load(f)
credentials = google.oauth2.credentials.Credentials.from_authorized_user_info(
credentials_dict
)
return credentials