18.7. API Auth
18.7.1. Authentication
from django.contrib.auth import authenticateauthenticate(username, password)Returns valid
userobject orNone
>>> from django.contrib.auth import authenticate
Valid credentials:
>>> #
... user = authenticate(username='admin', password='valid')
...
... type(user)
<class 'django.contrib.auth.models.User'>
Invalid credentials:
>>> #
... user = authenticate(username='admin', password='invalid')
...
... type(user)
<class 'NoneType'>
18.7.2. Login
from django.contrib.auth import loginlogin(request, user)Sets session data for authenticated user
Uses session middleware
Uses authentication middleware
Requires
requestobject and validuserobject fromauthenticate()
>>> #
... from django.contrib.auth import authenticate, login
...
... user = authenticate(username='admin', password='valid')
... login(request, user)
18.7.3. 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)