Ana2012 commited on
Commit
1ca9988
verified
1 Parent(s): 90a7c8d

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +25 -4
app/main.py CHANGED
@@ -108,8 +108,18 @@ def favicon():
108
  @app.get("/auth/google")
109
  def auth_google():
110
  try:
111
- authorization_url, _state = get_authorization_url()
 
 
 
 
 
 
 
 
 
112
  return RedirectResponse(url=authorization_url)
 
113
  except Exception as exc:
114
  return {
115
  "ok": False,
@@ -119,12 +129,23 @@ def auth_google():
119
 
120
 
121
  @app.get("/oauth2callback")
122
- def oauth2callback(code: str = Query(...)):
123
  try:
124
- flow = build_flow()
 
 
 
 
 
 
 
125
  flow.fetch_token(code=code)
 
126
  save_credentials(flow.credentials)
127
 
 
 
 
128
  return HTMLResponse(
129
  """
130
  <h3>Autorizacao concluida com sucesso.</h3>
@@ -132,12 +153,12 @@ def oauth2callback(code: str = Query(...)):
132
  <p>Voce ja pode fechar esta aba.</p>
133
  """
134
  )
 
135
  except Exception as exc:
136
  return HTMLResponse(
137
  f"""
138
  <h3>Erro ao concluir autorizacao Google.</h3>
139
  <p>{str(exc)}</p>
140
- <p>Verifique GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI e GOOGLE_SPREADSHEET_ID.</p>
141
  """,
142
  status_code=500,
143
  )
 
108
  @app.get("/auth/google")
109
  def auth_google():
110
  try:
111
+ flow = build_flow()
112
+ authorization_url, state = flow.authorization_url(
113
+ access_type="offline",
114
+ prompt="consent",
115
+ include_granted_scopes="true",
116
+ )
117
+
118
+ # 馃敟 salvar flow pelo state
119
+ oauth_flow_global[state] = flow
120
+
121
  return RedirectResponse(url=authorization_url)
122
+
123
  except Exception as exc:
124
  return {
125
  "ok": False,
 
129
 
130
 
131
  @app.get("/oauth2callback")
132
+ def oauth2callback(code: str = Query(...), state: str = Query(...)):
133
  try:
134
+ flow = oauth_flow_global.get(state)
135
+
136
+ if not flow:
137
+ return HTMLResponse(
138
+ "<h3>Erro: sessao OAuth expirada ou invalida.</h3>",
139
+ status_code=400,
140
+ )
141
+
142
  flow.fetch_token(code=code)
143
+
144
  save_credentials(flow.credentials)
145
 
146
+ # limpar da mem贸ria
147
+ oauth_flow_global.pop(state, None)
148
+
149
  return HTMLResponse(
150
  """
151
  <h3>Autorizacao concluida com sucesso.</h3>
 
153
  <p>Voce ja pode fechar esta aba.</p>
154
  """
155
  )
156
+
157
  except Exception as exc:
158
  return HTMLResponse(
159
  f"""
160
  <h3>Erro ao concluir autorizacao Google.</h3>
161
  <p>{str(exc)}</p>
 
162
  """,
163
  status_code=500,
164
  )