from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
from django.contrib.auth.models import User

class OIDCBearerTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth = request.META.get('HTTP_AUTHORIZATION', '')
        if not auth.startswith('Bearer '):
            return None
        token = auth.split(' ')[1]

        backend = OIDCAuthenticationBackend()

        try:
            claims = backend.verify_token(token)
        except Exception as e:
            raise AuthenticationFailed(f'Invalid token: {e}')

        user = backend.filter_users_by_claims(claims).first()
        if not user:
            raise AuthenticationFailed(f'Unknown user: {claims}')
        return (user, None)
