-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup_google_auth.py
117 lines (101 loc) · 4.41 KB
/
setup_google_auth.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import os
import sys
import json
from pathlib import Path
SCOPES = ['https://www.googleapis.com/auth/calendar']
def get_redirect_uri():
"""Get the appropriate redirect URI based on the environment"""
if os.getenv('RENDER'):
# Wenn auf Render deployed
return "https://solar-calendar-api.onrender.com/oauth2callback"
# Lokale Entwicklung
return "http://localhost"
def setup_google_calendar():
"""Generate Google Calendar tokens for authentication"""
try:
# Get the absolute path of the project directory
project_dir = Path(__file__).parent.absolute()
# In production, get credentials from environment variable
if os.getenv('RENDER'):
creds_content = json.loads(os.getenv('GOOGLE_CREDENTIALS', '{}'))
else:
credentials_path = project_dir / 'credentials.json'
print(f"Project directory: {project_dir}")
print(f"Looking for credentials.json at: {credentials_path}")
if not credentials_path.exists():
print(f"Error: credentials.json not found at {credentials_path}!")
print("\nPlease ensure credentials.json exists with this content:")
print("""{
"installed": {
"client_id": "your-client-id",
"project_id": "your-project-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "your-client-secret",
"redirect_uris": ["http://localhost"]
}
}""")
return
# Read and validate credentials file
try:
with credentials_path.open('r') as f:
creds_content = json.load(f)
except json.JSONDecodeError as e:
print(f"Error: credentials.json contains invalid JSON: {str(e)}")
return
except Exception as e:
print(f"Error reading credentials.json: {str(e)}")
return
if 'installed' not in creds_content:
print("Error: Invalid credentials format! Missing 'installed' key.")
return
print("Successfully read credentials")
# Import here to avoid errors if not installed
try:
from google_auth_oauthlib.flow import InstalledAppFlow
except ImportError:
print("Error: google-auth-oauthlib not installed!")
print("Please install it with: pip install google-auth-oauthlib")
return
# Create flow
try:
flow = InstalledAppFlow.from_client_secrets_file(
json.dumps(creds_content), # Convert dict to JSON string
SCOPES,
redirect_uri=get_redirect_uri()
)
print("\nStarting OAuth flow...")
print("A browser window should open automatically.")
print("If it doesn't, please check your terminal for the authorization URL.")
creds = flow.run_local_server(port=0)
print("OAuth flow completed successfully!")
# Create credentials dict
credentials_dict = {
"token": creds.token,
"refresh_token": creds.refresh_token,
"token_uri": creds.token_uri,
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"scopes": creds.scopes
}
# Save tokens
tokens_path = project_dir / 'google_tokens.json'
with tokens_path.open('w') as f:
json.dump(credentials_dict, f, indent=2)
print("\nAuthentication successful!")
print("\nAdd this to your .env file as GOOGLE_CALENDAR_CREDENTIALS:")
print(json.dumps(credentials_dict, indent=2))
print(f"\nTokens also saved to: {tokens_path}")
except Exception as e:
print(f"\nError during OAuth flow: {str(e)}")
except Exception as e:
print(f"\nUnexpected error: {str(e)}")
print("\nDebug information:")
print(f"Python version: {sys.version}")
print(f"Script location: {__file__}")
print("Python path:")
for path in sys.path:
print(f" {path}")
if __name__ == "__main__":
setup_google_calendar()