ram-lexsi commited on
Commit
5f7cb06
·
verified ·
1 Parent(s): 1e480eb

Sign in inside the Space page automatically; no new tab

Browse files
Files changed (1) hide show
  1. app.py +4 -4
app.py CHANGED
@@ -204,14 +204,14 @@ def login(request: Request):
204
  @app.get("/login/callback")
205
  def callback(request: Request, code: str = "", state: str = ""):
206
  if not code or state != request.session.pop("state", None):
207
- raise HTTPException(400, "login failed, please try again")
208
  tok = httpx.post(f"{PROVIDER}/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), timeout=20,
209
  data={"grant_type": "authorization_code", "code": code,
210
  "redirect_uri": f"https://{SPACE_HOST}/login/callback"}).json()
211
  info = httpx.get(f"{PROVIDER}/oauth/userinfo", timeout=20,
212
  headers={"Authorization": f"Bearer {tok['access_token']}"}).json()
213
  request.session["user"] = info["preferred_username"]
214
- return RedirectResponse("/")
215
 
216
 
217
  @app.get("/logout")
@@ -252,10 +252,10 @@ def index(request: Request):
252
  u = current_user(request)
253
  if not u:
254
  url = f"https://{SPACE_HOST}/login" if SPACE_HOST else "/login"
255
- if request.headers.get("sec-fetch-dest") == "document": # opened directly, not inside the HF iframe: just log in
256
  return RedirectResponse(url)
257
  return HTMLResponse(gate_page("Judges only", "Sign in with the Hugging Face account you were invited with.",
258
- f'<a href="{url}" target="_blank" rel="noopener">Sign in with Hugging Face</a>'),
259
  status_code=401, headers={"Cache-Control": "no-store"})
260
  if u.lower() not in JUDGES:
261
  import html
 
204
  @app.get("/login/callback")
205
  def callback(request: Request, code: str = "", state: str = ""):
206
  if not code or state != request.session.pop("state", None):
207
+ return RedirectResponse("/?li=retry") # cookie didn't stick: show the button instead of looping
208
  tok = httpx.post(f"{PROVIDER}/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), timeout=20,
209
  data={"grant_type": "authorization_code", "code": code,
210
  "redirect_uri": f"https://{SPACE_HOST}/login/callback"}).json()
211
  info = httpx.get(f"{PROVIDER}/oauth/userinfo", timeout=20,
212
  headers={"Authorization": f"Bearer {tok['access_token']}"}).json()
213
  request.session["user"] = info["preferred_username"]
214
+ return RedirectResponse("/?li=1")
215
 
216
 
217
  @app.get("/logout")
 
252
  u = current_user(request)
253
  if not u:
254
  url = f"https://{SPACE_HOST}/login" if SPACE_HOST else "/login"
255
+ if not request.query_params.get("li"): # first visit: sign in right here (inside the HF page too), no click
256
  return RedirectResponse(url)
257
  return HTMLResponse(gate_page("Judges only", "Sign in with the Hugging Face account you were invited with.",
258
+ f'<a href="{url}">Sign in with Hugging Face</a>'),
259
  status_code=401, headers={"Cache-Control": "no-store"})
260
  if u.lower() not in JUDGES:
261
  import html