from django.conf import settings from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ServiceBrokerAuthentication(authentication.BaseAuthentication): def authenticate(self, request): auth = request.META.get("HTTP_AUTHORIZATION") if not auth: return None try: import base64 auth_type, auth_string = auth.split(" ") if auth_type.lower() != "basic": return None decoded = base64.b64decode(auth_string).decode("utf-8") username, password = decoded.split(":") if ( username == settings.BROKER_USERNAME and password == settings.BROKER_PASSWORD ): # Use a dummy user for authentication user = User(username=username, is_staff=True) return (user, None) except Exception as e: raise exceptions.AuthenticationFailed("Invalid credentials") raise exceptions.AuthenticationFailed("Invalid credentials")