Spaces:
Running
Running
Download app/core/utils/jwt_parser.py from MuhammadMahmoud/Aoun-Ai: direct link, hf CLI and curl.
- Browser
- Download file 2.36 kB
-
https://huggingface.co/spaces/MuhammadMahmoud/Aoun-Ai/resolve/main/app/core/utils/jwt_parser.py
- Command line
-
hf download hf://spaces/MuhammadMahmoud/Aoun-Ai/app/core/utils/jwt_parser.py
-
curl -L -o jwt_parser.py https://huggingface.co/spaces/MuhammadMahmoud/Aoun-Ai/resolve/main/app/core/utils/jwt_parser.py
2.36 kB
| import base64 | |
| import json | |
| import logging | |
| from typing import Dict, Any | |
| logger = logging.getLogger(__name__) | |
| def extract_context_from_token(token: str) -> Dict[str, Any]: | |
| """ | |
| Extracts the user role, FamilyId, and AssociationId from a JWT token. | |
| This is strictly for UX purposes (System Prompt & Tool Filtering) | |
| and to pass internal headers to the backend without relying on frontend payload. | |
| Security is still enforced entirely by ASP.NET. | |
| """ | |
| context = { | |
| "role": "Family", # Default to Family | |
| "family_id": None, | |
| "association_id": None, | |
| "email": None, | |
| "display_name": None | |
| } | |
| if not token: | |
| return context | |
| try: | |
| parts = token.split('.') | |
| if len(parts) != 3: | |
| return context | |
| payload_b64 = parts[1] | |
| # Add padding if needed | |
| payload_b64 += "=" * ((4 - len(payload_b64) % 4) % 4) | |
| payload_json = base64.urlsafe_b64decode(payload_b64).decode('utf-8') | |
| payload = json.loads(payload_json) | |
| # ASP.NET commonly uses these claim keys for roles | |
| role = payload.get("role") or payload.get("http://schemas.microsoft.com/ws/2008/06/identity/claims/role") | |
| if isinstance(role, list): | |
| role = role[0] | |
| if role and "Association" in role: | |
| context["role"] = "Association" | |
| elif role and "Admin" in role: | |
| context["role"] = "Admin" | |
| # Extract specific IDs | |
| context["family_id"] = payload.get("FamilyId") | |
| context["association_id"] = payload.get("AssociationId") | |
| # Extract Email and Name | |
| context["email"] = payload.get("email") or payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress") | |
| context["display_name"] = payload.get("given_name") or payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname") or payload.get("name") or payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name") | |
| except Exception as e: | |
| logger.error("Failed to decode JWT context: %s", e) | |
| return context | |
| # Keep backward compatibility if anything else imports it | |
| def extract_role_from_token(token: str) -> str: | |
| return extract_context_from_token(token)["role"] | |