Ana2012 commited on
Commit
bb41bc4
·
verified ·
1 Parent(s): 0b7ca99

Update app/google_oauth.py

Browse files
Files changed (1) hide show
  1. app/google_oauth.py +46 -38
app/google_oauth.py CHANGED
@@ -12,10 +12,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
- OAUTH_TEMP = {}
19
 
20
  class GoogleOAuthError(RuntimeError):
21
  pass
@@ -38,8 +39,7 @@ def _resolve_data_dir():
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
 
@@ -61,6 +61,7 @@ def _client_config():
61
  }.items()
62
  if not value
63
  ]
 
64
  if missing:
65
  raise GoogleOAuthError("Variaveis OAuth ausentes: " + ", ".join(missing))
66
 
@@ -70,23 +71,14 @@ def _client_config():
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
-
82
- flow = Flow.from_client_config(
83
- _client_config(),
84
- scopes=SCOPES,
85
- state=state,
86
- autogenerate_code_verifier=False,
87
- )
88
-
89
- flow.redirect_uri = redirect_uri
90
  return flow
91
 
92
 
@@ -99,16 +91,22 @@ def get_authorization_url():
99
  include_granted_scopes="true",
100
  )
101
 
102
- return authorization_url, state
103
 
104
 
105
  def save_credentials(credentials):
 
 
 
 
 
106
  token_path = get_token_path()
107
  token_path.write_text(credentials.to_json(), encoding="utf-8")
108
 
109
 
110
  def load_credentials():
111
  token_path = get_token_path()
 
112
  if not token_path.exists():
113
  return None
114
 
@@ -133,6 +131,7 @@ def load_credentials():
133
 
134
  def get_sheets_service():
135
  credentials = load_credentials()
 
136
  if credentials is None:
137
  raise GoogleAuthRequiredError(
138
  "Google Sheets nao autorizado. Acesse /auth/google primeiro."
@@ -143,33 +142,42 @@ def get_sheets_service():
143
 
144
  def append_feedback_to_sheet(feedback_data):
145
  spreadsheet_id = os.environ.get("GOOGLE_SPREADSHEET_ID", "").strip()
 
146
  if not spreadsheet_id:
147
  raise GoogleOAuthError("GOOGLE_SPREADSHEET_ID nao configurado.")
148
 
149
  service = get_sheets_service()
 
150
  fields = [
151
- "timestamp",
152
- "query",
153
- "product_id",
154
- "product_name",
155
- "rating",
156
- "is_helpful",
157
- "note",
158
- "categoria_inferida",
159
- "feedback",
160
- "motivo",
161
- "score_final",
162
- "score_semantico",
163
- "bonus_lexical",
164
- "penalidade_feedback",
165
- "user_message",
166
- ]
 
 
 
 
167
  row = [[str(feedback_data.get(field, "") or "") for field in fields]]
168
 
169
- return service.spreadsheets().values().append(
170
- spreadsheetId=spreadsheet_id,
171
- range="Feedback!A:Z",
172
- valueInputOption="USER_ENTERED",
173
- insertDataOption="INSERT_ROWS",
174
- body={"values": row},
175
- ).execute()
 
 
 
 
12
  "https://www.googleapis.com/auth/spreadsheets",
13
  "https://www.googleapis.com/auth/drive.file",
14
  ]
15
+
16
  TOKEN_FILENAME = "google_token.json"
17
  DATA_DIR = Path("/data")
18
  FALLBACK_DATA_DIR = Path(tempfile.gettempdir()) / "tcc2_agent"
19
+
20
 
21
  class GoogleOAuthError(RuntimeError):
22
  pass
 
39
  continue
40
 
41
  raise GoogleOAuthError(
42
+ "Nao foi possivel criar um diretorio para armazenar o token OAuth."
 
43
  )
44
 
45
 
 
61
  }.items()
62
  if not value
63
  ]
64
+
65
  if missing:
66
  raise GoogleOAuthError("Variaveis OAuth ausentes: " + ", ".join(missing))
67
 
 
71
  "client_secret": client_secret,
72
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
73
  "token_uri": "https://oauth2.googleapis.com/token",
 
74
  "redirect_uris": [redirect_uri],
75
  }
76
  }
77
 
78
 
79
  def build_flow(state=None):
80
+ flow = Flow.from_client_config(_client_config(), scopes=SCOPES, state=state)
81
+ flow.redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI")
 
 
 
 
 
 
 
 
82
  return flow
83
 
84
 
 
91
  include_granted_scopes="true",
92
  )
93
 
94
+ return authorization_url, state # importante retornar state
95
 
96
 
97
  def save_credentials(credentials):
98
+ if not credentials.refresh_token:
99
+ raise GoogleOAuthError(
100
+ "Refresh token nao recebido. Revogue o acesso e autorize novamente."
101
+ )
102
+
103
  token_path = get_token_path()
104
  token_path.write_text(credentials.to_json(), encoding="utf-8")
105
 
106
 
107
  def load_credentials():
108
  token_path = get_token_path()
109
+
110
  if not token_path.exists():
111
  return None
112
 
 
131
 
132
  def get_sheets_service():
133
  credentials = load_credentials()
134
+
135
  if credentials is None:
136
  raise GoogleAuthRequiredError(
137
  "Google Sheets nao autorizado. Acesse /auth/google primeiro."
 
142
 
143
  def append_feedback_to_sheet(feedback_data):
144
  spreadsheet_id = os.environ.get("GOOGLE_SPREADSHEET_ID", "").strip()
145
+
146
  if not spreadsheet_id:
147
  raise GoogleOAuthError("GOOGLE_SPREADSHEET_ID nao configurado.")
148
 
149
  service = get_sheets_service()
150
+
151
  fields = [
152
+ "timestamp",
153
+ "search_id",
154
+ "query",
155
+ "rank",
156
+ "product_id",
157
+ "product_name",
158
+ "categoria_inferida",
159
+ "categoria_produto",
160
+ "rating",
161
+ "is_helpful",
162
+ "feedback",
163
+ "motivo",
164
+ "score_final",
165
+ "score_semantico",
166
+ "bonus_lexical",
167
+ "penalidade_feedback",
168
+ "user_message",
169
+ "note",
170
+ ]
171
+
172
  row = [[str(feedback_data.get(field, "") or "") for field in fields]]
173
 
174
+ try:
175
+ return service.spreadsheets().values().append(
176
+ spreadsheetId=spreadsheet_id,
177
+ range="Feedback!A:Z",
178
+ valueInputOption="USER_ENTERED",
179
+ insertDataOption="INSERT_ROWS",
180
+ body={"values": row},
181
+ ).execute()
182
+ except Exception as e:
183
+ raise GoogleOAuthError(f"Erro ao enviar para Google Sheets: {e}")