Hitakshi26 commited on
Commit
b40b09c
·
1 Parent(s): e4881ef

Fix HF login crash by allowing guest fallback

Browse files
Files changed (2) hide show
  1. src/backend/auth.py +50 -34
  2. src/frontend/ui.py +5 -5
src/backend/auth.py CHANGED
@@ -2,51 +2,67 @@ import os
2
  import gradio as gr
3
 
4
 
5
- def _get_headers_dict(request: gr.Request) -> dict:
6
- h = getattr(request, "headers", None) or {}
7
- # Normalize keys to lowercase
8
- out = {}
9
- try:
10
- for k, v in dict(h).items():
11
- out[str(k).lower()] = v
12
- except Exception:
13
- return {}
14
- return out
15
 
16
 
17
- def _first_value(v):
18
- # Some frameworks store header values as lists
19
- if isinstance(v, (list, tuple)) and v:
20
- return v[0]
21
- return v
22
-
23
-
24
- def require_login(request: gr.Request) -> str:
25
  """
26
- Returns a stable username for storage paths.
27
- Works in HF Spaces and local dev.
28
  """
29
- # 1) Best-case (some Gradio versions populate this)
 
 
 
30
  username = getattr(request, "username", None)
31
  if username:
32
  return str(username)
33
 
34
- # 2) HF proxy headers (varies by setup)
35
- headers = _get_headers_dict(request)
36
-
37
- for key in [
38
  "x-forwarded-user",
39
  "x-hf-user",
40
  "x-forwarded-preferred-username",
41
  "x-auth-request-preferred-username",
42
- ]:
43
- val = _first_value(headers.get(key))
44
- if val:
45
- return str(val)
46
-
47
- # 3) Local/dev fallback (so app doesn't hard-crash during dev)
48
- # HF Spaces usually sets SPACE_ID; locally it won't exist.
49
- if os.getenv("SPACE_ID") is None and os.getenv("HF_SPACE_ID") is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  return "localuser"
51
 
52
- raise gr.Error("Please log in using 'Sign in with Hugging Face' to use this app.")
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
 
4
 
5
+ def _header_get(headers: dict, key: str):
6
+ """Case-insensitive header lookup."""
7
+ if not headers:
8
+ return None
9
+ lk = key.lower()
10
+ for k, v in headers.items():
11
+ if str(k).lower() == lk:
12
+ return v
13
+ return None
 
14
 
15
 
16
+ def get_username_from_request(request: gr.Request) -> str | None:
 
 
 
 
 
 
 
17
  """
18
+ Try multiple ways to extract username from HF Spaces OAuth / proxy.
19
+ Different Gradio + Spaces versions expose this differently.
20
  """
21
+ if request is None:
22
+ return None
23
+
24
+ # 1) Best-case: gradio sets request.username
25
  username = getattr(request, "username", None)
26
  if username:
27
  return str(username)
28
 
29
+ # 2) Headers (varies by HF proxy / auth config)
30
+ headers = getattr(request, "headers", None) or {}
31
+ for key in (
 
32
  "x-forwarded-user",
33
  "x-hf-user",
34
  "x-forwarded-preferred-username",
35
  "x-auth-request-preferred-username",
36
+ "hf-user",
37
+ ):
38
+ v = _header_get(headers, key)
39
+ if v:
40
+ return str(v)
41
+
42
+ # 3) Some deployments put user info in query params / cookies (rare)
43
+ # Keep simple: if not found, return None
44
+ return None
45
+
46
+
47
+ def require_login(request: gr.Request) -> str:
48
+ """
49
+ 'Strict' login:
50
+ - If REQUIRE_LOGIN=1, enforce that we got a username.
51
+ - Otherwise, gracefully fall back to a guest user (so the app runs).
52
+ """
53
+ username = get_username_from_request(request)
54
+ if username:
55
+ return username
56
+
57
+ # Local/dev always allow
58
+ if os.getenv("HF_SPACE_ID") is None:
59
  return "localuser"
60
 
61
+ # On Spaces: optionally enforce
62
+ if os.getenv("REQUIRE_LOGIN", "0") == "1":
63
+ raise gr.Error("Please log in using 'Sign in with Hugging Face' to use this app.")
64
+
65
+ # Default: allow guest mode so the app works
66
+ # NOTE: single shared guest account. If you want per-user separation without auth:
67
+ # use request.client.host or a random session id (but keep simple for submission).
68
+ return "guest"
src/frontend/ui.py CHANGED
@@ -20,8 +20,8 @@ def build_app():
20
  with gr.Blocks(title="NotebookLM Clone") as demo:
21
  gr.Markdown("# 📓 NotebookLM Clone (HF Auth + Chroma + RAG)")
22
 
23
- login = gr.LoginButton()
24
- login.activate()
25
 
26
  username_state = gr.State("")
27
 
@@ -69,10 +69,10 @@ def build_app():
69
 
70
  # ---------- LOAD ----------
71
  def on_load(request: gr.Request):
72
- username = require_login(request)
73
  dd, chat, arts = ui_bootstrap(username)
74
- # Return user_box value directly so it always shows
75
- return username, username, dd, chat, arts
76
 
77
  demo.load(
78
  on_load,
 
20
  with gr.Blocks(title="NotebookLM Clone") as demo:
21
  gr.Markdown("# 📓 NotebookLM Clone (HF Auth + Chroma + RAG)")
22
 
23
+ gr.LoginButton().activate()
24
+
25
 
26
  username_state = gr.State("")
27
 
 
69
 
70
  # ---------- LOAD ----------
71
  def on_load(request: gr.Request):
72
+ username = require_login(request) # will fall back to "guest" if missing
73
  dd, chat, arts = ui_bootstrap(username)
74
+ return username, dd, chat, arts
75
+
76
 
77
  demo.load(
78
  on_load,