""" Django Ninja Security Classes for JWT Authentication Provides authentication classes that can be used with Django Ninja's auth parameter to protect API endpoints. """ from django.http import HttpRequest from ninja.security import HttpBearer from .tokens import decode_token, JWTUser class JWTAuth(HttpBearer): """ JWT Bearer token authentication for Django Ninja. Usage: from ninja_jwt_session import jwt_auth @api.get("/protected/", auth=jwt_auth) def protected_endpoint(request): return {"user_id": request.user.id} Or globally: api = NinjaExtraAPI(auth=[django_auth, jwt_auth]) The token must be passed in the Authorization header: Authorization: Bearer IMPORTANT: This is stateless - no database query is made. request.user is a JWTUser object with id, is_staff, is_superuser. If you need the full User object, query it explicitly: user = User.objects.get(pk=request.user.id) """ def authenticate(self, request: HttpRequest, token: str): """ Validate the JWT and return a JWTUser if valid. Returns None (authentication failed) if: - Token is invalid or expired - Token is not an access token Note: No database query is made. The JWTUser is created from token claims. This is truly stateless authentication. """ # Decode and validate the token payload = decode_token(token, expected_type="access") if payload is None: return None # Create JWTUser from token claims - NO DATABASE QUERY jwt_user = JWTUser(payload) # Set request.user for compatibility with code expecting it request.user = jwt_user return jwt_user # Singleton instance for convenience jwt_auth = JWTAuth()