from django.contrib.auth import get_user_model
from django.conf import settings
from ninja.security import HttpBearer
import jwt

User = get_user_model()

class AuthBearer(HttpBearer):
    def authenticate(self, request, token):
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            user = User.objects.get(id=payload['user_id'])
            request.user = user
            return token
        except (jwt.PyJWTError, User.DoesNotExist):
            return None
