funkwhale/api/funkwhale_api/federation/authentication.py

42 wiersze
1.3 KiB
Python
Czysty Zwykły widok Historia

import cryptography
from django.contrib.auth.models import AnonymousUser
2018-06-10 08:55:16 +00:00
from rest_framework import authentication, exceptions
2018-06-10 08:55:16 +00:00
from . import actors, keys, signing, utils
class SignatureAuthentication(authentication.BaseAuthentication):
def authenticate_actor(self, request):
headers = utils.clean_wsgi_headers(request.META)
try:
2018-06-09 13:36:16 +00:00
signature = headers["Signature"]
key_id = keys.get_key_id_from_signature_header(signature)
except KeyError:
return
except ValueError as e:
raise exceptions.AuthenticationFailed(str(e))
try:
2018-06-09 13:36:16 +00:00
actor = actors.get_actor(key_id.split("#")[0])
except Exception as e:
raise exceptions.AuthenticationFailed(str(e))
if not actor.public_key:
2018-06-09 13:36:16 +00:00
raise exceptions.AuthenticationFailed("No public key found")
try:
2018-06-09 13:36:16 +00:00
signing.verify_django(request, actor.public_key.encode("utf-8"))
except cryptography.exceptions.InvalidSignature:
2018-06-09 13:36:16 +00:00
raise exceptions.AuthenticationFailed("Invalid signature")
return actor
def authenticate(self, request):
2018-06-09 13:36:16 +00:00
setattr(request, "actor", None)
actor = self.authenticate_actor(request)
if not actor:
return
user = AnonymousUser()
2018-06-09 13:36:16 +00:00
setattr(request, "actor", actor)
return (user, None)