Skip to content
Snippets Groups Projects
auth.py 1.1 KiB
Newer Older
  • Learn to ignore specific revisions
  • from urllib.parse import parse_qs
    
    
    from django.contrib.auth.models import AnonymousUser
    
    from rest_framework import exceptions
    from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
    
    
    from funkwhale_api.users.models import User
    
    
    
    class TokenHeaderAuth(BaseJSONWebTokenAuthentication):
        def get_jwt_value(self, request):
    
            try:
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                qs = request.get("query_string", b"").decode("utf-8")
    
                parsed = parse_qs(qs)
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                token = parsed["token"][0]
    
            except KeyError:
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                raise exceptions.AuthenticationFailed("No token")
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                raise exceptions.AuthenticationFailed("Empty token")
    
    
            return token
    
    
    class TokenAuthMiddleware:
        def __init__(self, inner):
            # Store the ASGI application we were passed
            self.inner = inner
    
        def __call__(self, scope):
            auth = TokenHeaderAuth()
            try:
                user, token = auth.authenticate(scope)
    
            except (User.DoesNotExist, exceptions.AuthenticationFailed):
    
                user = AnonymousUser()
    
    
    Eliot Berriot's avatar
    Eliot Berriot committed
            scope["user"] = user
    
            return self.inner(scope)