Verify a JWT token string directly (for WebSocket auth). Returns AuthenticatedUser or None if invalid.
(token: str)
| 109 | AuthUser = Annotated[AuthenticatedUser, Depends(get_current_user)] |
| 110 | |
| 111 | async def verify_token_from_string(token: str) -> Optional[AuthenticatedUser]: |
| 112 | """ |
| 113 | Verify a JWT token string directly (for WebSocket auth). |
| 114 | Returns AuthenticatedUser or None if invalid. |
| 115 | """ |
| 116 | try: |
| 117 | signing_key = jwks_client.get_signing_key_from_jwt(token) |
| 118 | |
| 119 | payload = jwt.decode( |
| 120 | token, |
| 121 | signing_key.key, |
| 122 | algorithms=ALGORITHMS, |
| 123 | audience=API_AUDIENCE, |
| 124 | issuer=ISSUER, |
| 125 | options={"verify_exp": True} |
| 126 | ) |
| 127 | |
| 128 | user_id = payload.get("sub") |
| 129 | if user_id is None: |
| 130 | return None |
| 131 | |
| 132 | app_metadata_claim = f"{CUSTOM_CLAIM_NAMESPACE}app_metadata" |
| 133 | app_metadata = payload.get(app_metadata_claim) or {} |
| 134 | |
| 135 | email_claim = f"{CUSTOM_CLAIM_NAMESPACE}email" |
| 136 | |
| 137 | return AuthenticatedUser( |
| 138 | id=user_id, |
| 139 | email=payload.get(email_claim), |
| 140 | is_pro=app_metadata.get("is_pro", False), |
| 141 | is_max=app_metadata.get("is_max", False), |
| 142 | is_plus=app_metadata.get("is_plus", False), |
| 143 | app_metadata=app_metadata |
| 144 | ) |
| 145 | |
| 146 | except (PyJWTError, Exception) as e: |
| 147 | logger.warning(f"WebSocket token validation failed: {e}") |
| 148 | return None |
no test coverage detected