Django: Basic Auth for one view (avoiding middleware) ¶
Adapted from:
"Django: Basic Auth for one view (avoid middleware)"
file decorators.py:
import base64 from django.http import HttpResponse from django.contrib.auth import authenticate def basicauth(view): """ Adapted from: "Django: Basic Auth for one view (avoid middleware)" https://stackoverflow.com/questions/46426683/django-basic-auth-for-one-view-avoid-middleware#47902577 """ def wrap(request, *args, **kwargs): if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).decode( "utf8" ).split(':', 1) user = authenticate(username=uname, password=passwd) if user is not None and user.is_active: request.user = user return view(request, *args, **kwargs) response = HttpResponse() response.status_code = 401 response['WWW-Authenticate'] = 'Basic realm="{}"'.format( #settings.BASIC_AUTH_REALM 'api' ) return response return wrap
file view.py:
from django.http import JsonResponse from .decorators import basicauth @basicauth def get_data(request, query_name): try: if not request.user.is_authenticated: raise Exception("Authentication required") ... data = { whatever } response = JsonResponse( { "success": True, "data": data, } ) except Exception as e: response = JsonResponse( { "success": False, "errors": [ { "status": 400, "source": { "view": "get_dw_data()", "traceback": traceback.format_exc() if config.EXCHANGE_API_TRACEBACK else "", }, "title": "Error", "detail": str(e), } ], }, safe=True, status=400, ) return response