Aoun-Ai / app /core /utils /jwt_parser.py
MuhammadMahmoud's picture
feat: parse user context from JWT token locally instead of calling API
373ef0a
Raw History Blame Contribute Delete
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"]