Ana2012 commited on
Commit
aa168a1
·
verified ·
1 Parent(s): fd0a4c0

Update app/google_oauth.py

Browse files
Files changed (1) hide show
  1. app/google_oauth.py +163 -144
app/google_oauth.py CHANGED
@@ -1,144 +1,163 @@
1
- import json
2
- import os
3
- from pathlib import Path
4
-
5
- from google.auth.transport.requests import Request
6
- from google.oauth2.credentials import Credentials
7
- from google_auth_oauthlib.flow import Flow
8
- from googleapiclient.discovery import build
9
-
10
- SCOPES = [
11
- "https://www.googleapis.com/auth/spreadsheets",
12
- "https://www.googleapis.com/auth/drive.file",
13
- ]
14
- TOKEN_FILENAME = "google_token.json"
15
- DATA_DIR = Path("/data")
16
-
17
-
18
- class GoogleOAuthError(RuntimeError):
19
- pass
20
-
21
-
22
- class GoogleAuthRequiredError(GoogleOAuthError):
23
- pass
24
-
25
-
26
- def get_token_path():
27
- DATA_DIR.mkdir(parents=True, exist_ok=True)
28
- return DATA_DIR / TOKEN_FILENAME
29
-
30
-
31
- def _client_config():
32
- client_id = os.environ.get("GOOGLE_CLIENT_ID", "").strip()
33
- client_secret = os.environ.get("GOOGLE_CLIENT_SECRET", "").strip()
34
- redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
35
-
36
- missing = [
37
- name
38
- for name, value in {
39
- "GOOGLE_CLIENT_ID": client_id,
40
- "GOOGLE_CLIENT_SECRET": client_secret,
41
- "GOOGLE_REDIRECT_URI": redirect_uri,
42
- }.items()
43
- if not value
44
- ]
45
- if missing:
46
- raise GoogleOAuthError("Variaveis OAuth ausentes: " + ", ".join(missing))
47
-
48
- return {
49
- "web": {
50
- "client_id": client_id,
51
- "client_secret": client_secret,
52
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
53
- "token_uri": "https://oauth2.googleapis.com/token",
54
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
55
- "redirect_uris": [redirect_uri],
56
- }
57
- }
58
-
59
-
60
- def build_flow(state=None):
61
- redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
62
- flow = Flow.from_client_config(_client_config(), scopes=SCOPES, state=state)
63
- flow.redirect_uri = redirect_uri
64
- return flow
65
-
66
-
67
- def get_authorization_url():
68
- flow = build_flow()
69
- authorization_url, state = flow.authorization_url(
70
- access_type="offline",
71
- prompt="consent",
72
- include_granted_scopes="true",
73
- )
74
- return authorization_url, state
75
-
76
-
77
- def save_credentials(credentials):
78
- token_path = get_token_path()
79
- token_path.write_text(credentials.to_json(), encoding="utf-8")
80
-
81
-
82
- def load_credentials():
83
- token_path = get_token_path()
84
- if not token_path.exists():
85
- return None
86
-
87
- try:
88
- payload = json.loads(token_path.read_text(encoding="utf-8"))
89
- credentials = Credentials.from_authorized_user_info(payload, SCOPES)
90
- except Exception:
91
- return None
92
-
93
- if credentials.expired and credentials.refresh_token:
94
- try:
95
- credentials.refresh(Request())
96
- save_credentials(credentials)
97
- except Exception:
98
- return None
99
-
100
- if not credentials.valid:
101
- return None
102
-
103
- return credentials
104
-
105
-
106
- def get_sheets_service():
107
- credentials = load_credentials()
108
- if credentials is None:
109
- raise GoogleAuthRequiredError(
110
- "Google Sheets nao autorizado. Acesse /auth/google primeiro."
111
- )
112
-
113
- return build("sheets", "v4", credentials=credentials, cache_discovery=False)
114
-
115
-
116
- def append_feedback_to_sheet(feedback_data):
117
- spreadsheet_id = os.environ.get("GOOGLE_SPREADSHEET_ID", "").strip()
118
- if not spreadsheet_id:
119
- raise GoogleOAuthError("GOOGLE_SPREADSHEET_ID nao configurado.")
120
-
121
- service = get_sheets_service()
122
- fields = [
123
- "timestamp",
124
- "query",
125
- "product_id",
126
- "product_name",
127
- "categoria_inferida",
128
- "feedback",
129
- "motivo",
130
- "score_final",
131
- "score_semantico",
132
- "bonus_lexical",
133
- "penalidade_feedback",
134
- "user_message",
135
- ]
136
- row = [[str(feedback_data.get(field, "") or "") for field in fields]]
137
-
138
- return service.spreadsheets().values().append(
139
- spreadsheetId=spreadsheet_id,
140
- range="Feedback!A:Z",
141
- valueInputOption="USER_ENTERED",
142
- insertDataOption="INSERT_ROWS",
143
- body={"values": row},
144
- ).execute()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ from google.auth.transport.requests import Request
7
+ from google.oauth2.credentials import Credentials
8
+ from google_auth_oauthlib.flow import Flow
9
+ from googleapiclient.discovery import build
10
+
11
+ SCOPES = [
12
+ "https://www.googleapis.com/auth/spreadsheets",
13
+ "https://www.googleapis.com/auth/drive.file",
14
+ ]
15
+ TOKEN_FILENAME = "google_token.json"
16
+ DATA_DIR = Path("/data")
17
+ FALLBACK_DATA_DIR = Path(tempfile.gettempdir()) / "tcc2_agent"
18
+
19
+
20
+ class GoogleOAuthError(RuntimeError):
21
+ pass
22
+
23
+
24
+ class GoogleAuthRequiredError(GoogleOAuthError):
25
+ pass
26
+
27
+
28
+ def _resolve_data_dir():
29
+ preferred_dir = os.environ.get("GOOGLE_TOKEN_DIR", "").strip()
30
+ candidates = [Path(preferred_dir)] if preferred_dir else []
31
+ candidates.extend([DATA_DIR, FALLBACK_DATA_DIR])
32
+
33
+ for directory in candidates:
34
+ try:
35
+ directory.mkdir(parents=True, exist_ok=True)
36
+ return directory
37
+ except OSError:
38
+ continue
39
+
40
+ raise GoogleOAuthError(
41
+ "Nao foi possivel criar um diretorio para armazenar o token OAuth. "
42
+ "Defina GOOGLE_TOKEN_DIR para um caminho gravavel."
43
+ )
44
+
45
+
46
+ def get_token_path():
47
+ return _resolve_data_dir() / TOKEN_FILENAME
48
+
49
+
50
+ def _client_config():
51
+ client_id = os.environ.get("GOOGLE_CLIENT_ID", "").strip()
52
+ client_secret = os.environ.get("GOOGLE_CLIENT_SECRET", "").strip()
53
+ redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
54
+
55
+ missing = [
56
+ name
57
+ for name, value in {
58
+ "GOOGLE_CLIENT_ID": client_id,
59
+ "GOOGLE_CLIENT_SECRET": client_secret,
60
+ "GOOGLE_REDIRECT_URI": redirect_uri,
61
+ }.items()
62
+ if not value
63
+ ]
64
+ if missing:
65
+ raise GoogleOAuthError("Variaveis OAuth ausentes: " + ", ".join(missing))
66
+
67
+ return {
68
+ "web": {
69
+ "client_id": client_id,
70
+ "client_secret": client_secret,
71
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
72
+ "token_uri": "https://oauth2.googleapis.com/token",
73
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
74
+ "redirect_uris": [redirect_uri],
75
+ }
76
+ }
77
+
78
+
79
+ def build_flow(state=None):
80
+ redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
81
+ flow = Flow.from_client_config(_client_config(), scopes=SCOPES, state=state)
82
+ flow.redirect_uri = redirect_uri
83
+ return flow
84
+
85
+
86
+ def get_authorization_url():
87
+ flow = build_flow()
88
+ authorization_url, state = flow.authorization_url(
89
+ access_type="offline",
90
+ prompt="consent",
91
+ include_granted_scopes="true",
92
+ )
93
+ return authorization_url, state
94
+
95
+
96
+ def save_credentials(credentials):
97
+ token_path = get_token_path()
98
+ token_path.write_text(credentials.to_json(), encoding="utf-8")
99
+
100
+
101
+ def load_credentials():
102
+ token_path = get_token_path()
103
+ if not token_path.exists():
104
+ return None
105
+
106
+ try:
107
+ payload = json.loads(token_path.read_text(encoding="utf-8"))
108
+ credentials = Credentials.from_authorized_user_info(payload, SCOPES)
109
+ except Exception:
110
+ return None
111
+
112
+ if credentials.expired and credentials.refresh_token:
113
+ try:
114
+ credentials.refresh(Request())
115
+ save_credentials(credentials)
116
+ except Exception:
117
+ return None
118
+
119
+ if not credentials.valid:
120
+ return None
121
+
122
+ return credentials
123
+
124
+
125
+ def get_sheets_service():
126
+ credentials = load_credentials()
127
+ if credentials is None:
128
+ raise GoogleAuthRequiredError(
129
+ "Google Sheets nao autorizado. Acesse /auth/google primeiro."
130
+ )
131
+
132
+ return build("sheets", "v4", credentials=credentials, cache_discovery=False)
133
+
134
+
135
+ def append_feedback_to_sheet(feedback_data):
136
+ spreadsheet_id = os.environ.get("GOOGLE_SPREADSHEET_ID", "").strip()
137
+ if not spreadsheet_id:
138
+ raise GoogleOAuthError("GOOGLE_SPREADSHEET_ID nao configurado.")
139
+
140
+ service = get_sheets_service()
141
+ fields = [
142
+ "timestamp",
143
+ "query",
144
+ "product_id",
145
+ "product_name",
146
+ "categoria_inferida",
147
+ "feedback",
148
+ "motivo",
149
+ "score_final",
150
+ "score_semantico",
151
+ "bonus_lexical",
152
+ "penalidade_feedback",
153
+ "user_message",
154
+ ]
155
+ row = [[str(feedback_data.get(field, "") or "") for field in fields]]
156
+
157
+ return service.spreadsheets().values().append(
158
+ spreadsheetId=spreadsheet_id,
159
+ range="Feedback!A:Z",
160
+ valueInputOption="USER_ENTERED",
161
+ insertDataOption="INSERT_ROWS",
162
+ body={"values": row},
163
+ ).execute()