17.2. API Auth

17.2.1. Basic Auth

>>> 
... from http import HTTPStatus
... from base64 import b64decode
... from django.http import JsonResponse
... from django.views import View
... from django.contrib.auth import authenticate, login
... from .models import Customer
...
...
... class BasicAuthMixin:
...     def dispatch(self, *args, **kwargs):
...         if not request.user.is_authenticated:
...             try:
...                 self.authenticate()
...             except PermissionError:
...                 return JsonResponse(status=HTTPStatus.FORBIDDEN, data={'msg': 'Basic auth failed'})
...         return super().dispatch(*args, **kwargs)
...
...     def authenticate(self):
...         auth_header = self.request.META.get('HTTP_AUTHORIZATION')
...         if not auth_header:
...             raise PermissionError
...         auth_type, credentials = auth_header.split()
...         credentials = b64decode(credentials).decode()
...         username, password = credentials.split(':')
...         user = authenticate(self.request, username=username, password=password)
...         if user is not None:
...             login(self.request, user)
...         else:
...             raise PermissionError

Usage:

... class ContactJSON(BasicAuthMixin, View): ... def get(self, request, **kwargs): ... data = Customer.objects.all().values() ... return JsonResponse(status=HTTPStatus.OK, data=list(data), safe=False)