File size: 2,341 Bytes
21ca484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149a97d
 
 
21ca484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

# If modifying these scopes, delete the file token.json.
# Read-only access to the calendar:
# SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
# Full access to the calendar:
SCOPES = ["https://www.googleapis.com/auth/calendar.events"]

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
GOOGLE_API_DIR = os.path.join(PROJECT_ROOT, "api", "google_api")

def get_authentications_for_user(username, allow_logging_popup=False):
    authentications = {}
    
    if not os.path.isdir(os.path.join(GOOGLE_API_DIR, username)):
        raise FileNotFoundError(f"No existe el directorio para el usuario '{username}'. Ruta comprobada: {os.path.join(GOOGLE_API_DIR, username)}")
    for account in os.listdir(os.path.join(GOOGLE_API_DIR, username)):
        for filename in os.listdir(os.path.join(GOOGLE_API_DIR, username, account)):
            if filename.endswith(".json") and not "example" in filename:
                filepath = os.path.join(GOOGLE_API_DIR, username, account, filename)
                if "credential" in filename:
                    credential_path = filepath
                elif "token" in filename:
                    token_path = filepath
                    authentication = Credentials.from_authorized_user_file(filepath, SCOPES)
                else:
                    print(f"Unknown file type: {filepath}")
        if not authentication or not authentication.valid:
            if authentication and authentication.expired and authentication.refresh_token:
                authentication.refresh(Request())
            else:
                if allow_logging_popup:
                    flow = InstalledAppFlow.from_client_secrets_file(credential_path, SCOPES)
                    authentication = flow.run_local_server(port=0)
                else:
                    print(f"Unable to authenticate {account}. Logging pop-up not allowed. Please run the authentication flow.")
                    return None
            with open(token_path, 'w') as token_file:
                token_file.write(authentication.to_json())
        authentications[account] = authentication

    return authentications