MCPcopy Create free account
hub / github.com/Roy3838/Observer / get_current_user

Function get_current_user

api/auth.py:39–108  ·  view source on GitHub ↗

A FastAPI dependency that validates the Authorization token, and returns an AuthenticatedUser object with the user's ID and pro status. Raises HTTPException if validation fails.

(request: Request)

Source from the content-addressed store, hash-verified

37
38# --- The Updated FastAPI Dependency ---
39async def get_current_user(request: Request) -> AuthenticatedUser:
40 """
41 A FastAPI dependency that validates the Authorization token,
42 and returns an AuthenticatedUser object with the user's ID and pro status.
43 Raises HTTPException if validation fails.
44 """
45 credentials_exception = HTTPException(
46 status_code=status.HTTP_401_UNAUTHORIZED,
47 detail="Could not validate credentials",
48 headers={"WWW-Authenticate": "Bearer"},
49 )
50
51 auth_header = request.headers.get("Authorization")
52 if not auth_header or not auth_header.startswith("Bearer "):
53 logger.warning("Authorization header is missing or does not start with Bearer")
54 raise credentials_exception
55
56 token = auth_header.split(" ")[1]
57
58 try:
59 signing_key = jwks_client.get_signing_key_from_jwt(token)
60
61 payload = jwt.decode(
62 token,
63 signing_key.key,
64 algorithms=ALGORITHMS,
65 audience=API_AUDIENCE,
66 issuer=ISSUER,
67 options={"verify_exp": True}
68 )
69
70 user_id = payload.get("sub")
71 if user_id is None:
72 logger.warning("Token is valid but 'sub' (user ID) is missing.")
73 raise credentials_exception
74
75 # 1. Define the claim name for the whole metadata object
76 app_metadata_claim = f"{CUSTOM_CLAIM_NAMESPACE}app_metadata"
77
78 # 2. Get the metadata dictionary from the token (it will be None if not present)
79 app_metadata = payload.get(app_metadata_claim) or {} # Use empty dict as fallback
80
81 # 3. Get the specific values from the metadata dictionary
82 is_pro_status = app_metadata.get("is_pro", False)
83 is_max_status = app_metadata.get("is_max", False)
84 is_plus_status = app_metadata.get("is_plus", False)
85
86 # 4. Get email from namespaced claim (set by Auth0 Action)
87 email_claim = f"{CUSTOM_CLAIM_NAMESPACE}email"
88 user_email = payload.get(email_claim)
89
90 logger.info(f"User is pro: {is_pro_status}, is max: {is_max_status}, is plus: {is_plus_status}")
91
92 # Return the structured user data
93 return AuthenticatedUser(
94 id=user_id,
95 email=user_email,
96 is_pro=is_pro_status,

Callers

nothing calls this directly

Calls 3

AuthenticatedUserClass · 0.85
infoMethod · 0.80
errorMethod · 0.80

Tested by

no test coverage detected