Spaces:
Running
Running
Anirudh Esthuri
commited on
Commit
Β·
15dc14b
1
Parent(s):
ad65183
Improve HF token validation with better error messages and debugging
Browse files
app.py
CHANGED
|
@@ -361,18 +361,58 @@ with st.sidebar:
|
|
| 361 |
# Check if we're on Hugging Face Spaces (not local)
|
| 362 |
is_hf_space = os.getenv("SPACE_ID") is not None or os.getenv("HF_ENDPOINT") is not None
|
| 363 |
|
| 364 |
-
def validate_hf_token(token: str) -> tuple[bool, str]:
|
| 365 |
-
"""Validate HF token and return (is_valid, username)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
try:
|
| 367 |
-
|
| 368 |
-
|
| 369 |
if resp.status_code == 200:
|
| 370 |
user_data = resp.json()
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
|
| 377 |
if is_hf_space:
|
| 378 |
# On HF Spaces - require token authentication for security
|
|
@@ -390,14 +430,16 @@ with st.sidebar:
|
|
| 390 |
|
| 391 |
if st.button("Authenticate", use_container_width=True, type="primary"):
|
| 392 |
if token_input.strip():
|
| 393 |
-
|
|
|
|
| 394 |
if is_valid and username:
|
| 395 |
st.session_state.hf_authenticated_user = username
|
| 396 |
st.session_state.hf_token = token_input.strip() # Store for future use
|
| 397 |
st.success(f"β
Authenticated as **{username}**")
|
| 398 |
st.rerun()
|
| 399 |
else:
|
| 400 |
-
|
|
|
|
| 401 |
else:
|
| 402 |
st.error("Please enter your access token")
|
| 403 |
st.info("π‘ **Privacy Note:** Your token is stored only in this session and never shared.")
|
|
|
|
| 361 |
# Check if we're on Hugging Face Spaces (not local)
|
| 362 |
is_hf_space = os.getenv("SPACE_ID") is not None or os.getenv("HF_ENDPOINT") is not None
|
| 363 |
|
| 364 |
+
def validate_hf_token(token: str) -> tuple[bool, str, str]:
|
| 365 |
+
"""Validate HF token and return (is_valid, username, error_message)."""
|
| 366 |
+
token = token.strip()
|
| 367 |
+
if not token:
|
| 368 |
+
return False, "", "Token cannot be empty"
|
| 369 |
+
|
| 370 |
+
# Use the HF whoami endpoint
|
| 371 |
+
endpoint = "https://huggingface.co/api/whoami"
|
| 372 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 373 |
+
|
| 374 |
try:
|
| 375 |
+
resp = requests.get(endpoint, headers=headers, timeout=10)
|
| 376 |
+
|
| 377 |
if resp.status_code == 200:
|
| 378 |
user_data = resp.json()
|
| 379 |
+
# Try different possible username fields
|
| 380 |
+
username = (
|
| 381 |
+
user_data.get("name") or
|
| 382 |
+
user_data.get("username") or
|
| 383 |
+
user_data.get("user") or
|
| 384 |
+
""
|
| 385 |
+
)
|
| 386 |
+
if username:
|
| 387 |
+
return True, username, ""
|
| 388 |
+
else:
|
| 389 |
+
# Log the response for debugging
|
| 390 |
+
return False, "", f"Token validated but username not found. Please try regenerating your token."
|
| 391 |
+
elif resp.status_code == 401:
|
| 392 |
+
error_detail = ""
|
| 393 |
+
try:
|
| 394 |
+
error_data = resp.json()
|
| 395 |
+
error_detail = error_data.get("error", "")
|
| 396 |
+
except:
|
| 397 |
+
pass
|
| 398 |
+
return False, "", f"Invalid token (401 Unauthorized). {error_detail} Please check your token at https://huggingface.co/settings/tokens"
|
| 399 |
+
elif resp.status_code == 403:
|
| 400 |
+
return False, "", f"Token access denied (403 Forbidden). Please ensure your token has read permissions."
|
| 401 |
+
else:
|
| 402 |
+
error_text = ""
|
| 403 |
+
try:
|
| 404 |
+
error_data = resp.json()
|
| 405 |
+
error_text = error_data.get("error", resp.text[:100])
|
| 406 |
+
except:
|
| 407 |
+
error_text = resp.text[:100] if hasattr(resp, 'text') else f"Status {resp.status_code}"
|
| 408 |
+
return False, "", f"Authentication failed (Status {resp.status_code}): {error_text}"
|
| 409 |
+
|
| 410 |
+
except requests.exceptions.Timeout:
|
| 411 |
+
return False, "", "Request timed out. Please check your internet connection and try again."
|
| 412 |
+
except requests.exceptions.RequestException as e:
|
| 413 |
+
return False, "", f"Network error: {str(e)}. Please try again."
|
| 414 |
+
except Exception as e:
|
| 415 |
+
return False, "", f"Validation error: {str(e)}. Please try again."
|
| 416 |
|
| 417 |
if is_hf_space:
|
| 418 |
# On HF Spaces - require token authentication for security
|
|
|
|
| 430 |
|
| 431 |
if st.button("Authenticate", use_container_width=True, type="primary"):
|
| 432 |
if token_input.strip():
|
| 433 |
+
with st.spinner("Validating token..."):
|
| 434 |
+
is_valid, username, error_msg = validate_hf_token(token_input.strip())
|
| 435 |
if is_valid and username:
|
| 436 |
st.session_state.hf_authenticated_user = username
|
| 437 |
st.session_state.hf_token = token_input.strip() # Store for future use
|
| 438 |
st.success(f"β
Authenticated as **{username}**")
|
| 439 |
st.rerun()
|
| 440 |
else:
|
| 441 |
+
error_display = error_msg if error_msg else "Invalid token. Please check your Hugging Face access token."
|
| 442 |
+
st.error(f"β {error_display}")
|
| 443 |
else:
|
| 444 |
st.error("Please enter your access token")
|
| 445 |
st.info("π‘ **Privacy Note:** Your token is stored only in this session and never shared.")
|