Skip to content
Snippets Groups Projects
authentication.py 1.41 KiB
Newer Older
  • Learn to ignore specific revisions
  • import cryptography
    
    from django.contrib.auth.models import AnonymousUser
    
    from rest_framework import authentication
    from rest_framework import exceptions
    
    from . import actors
    from . import keys
    from . import signing
    
    
    
    class SignatureAuthentication(authentication.BaseAuthentication):
    
        def authenticate_actor(self, request):
            headers = utils.clean_wsgi_headers(request.META)
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                signature = headers["Signature"]
    
                key_id = keys.get_key_id_from_signature_header(signature)
            except KeyError:
    
            except ValueError as e:
                raise exceptions.AuthenticationFailed(str(e))
    
            try:
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                actor = actors.get_actor(key_id.split("#")[0])
    
            except Exception as e:
                raise exceptions.AuthenticationFailed(str(e))
    
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                raise exceptions.AuthenticationFailed("No public key found")
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                signing.verify_django(request, actor.public_key.encode("utf-8"))
    
            except cryptography.exceptions.InvalidSignature:
    
    Eliot Berriot's avatar
    Eliot Berriot committed
                raise exceptions.AuthenticationFailed("Invalid signature")
    
    
        def authenticate(self, request):
    
    Eliot Berriot's avatar
    Eliot Berriot committed
            setattr(request, "actor", None)
    
            actor = self.authenticate_actor(request)
    
            if not actor:
                return
    
            user = AnonymousUser()
    
    Eliot Berriot's avatar
    Eliot Berriot committed
            setattr(request, "actor", actor)
    
            return (user, None)