18.7. Ninja Auth

18.7.1. Schemas

>>> 
... from ninja import Schema
...
...
... class LoginRequest(Schema):
...     username: str
...     password: str
...
...     model_config = {
...         'json_schema_extra': {
...             'example': {
...                 'username': 'myusername',
...                 'password': 'mypassword'}}}
...
...
... class LoginResponse(Schema):
...     session_key: str
...
...     model_config = {
...         'json_schema_extra': {
...             'example': {
...                 'session_key': 'vr5wsex3wqiryc1xpt8dakjyvqzu1wuf'}}}
...
...
... class LogoutRequest(Schema):
...     session_key: str
...
...     model_config = {
...         'json_schema_extra': {
...             'example': {
...                 'session_key': 'vr5wsex3wqiryc1xpt8dakjyvqzu1wuf'}}}

18.7.2. API

>>> 
... from django.contrib.auth import authenticate, login, logout
... from django.contrib.sessions.models import Session
... from django.http import HttpRequest
... from ninja import Router
... from ninja.security import APIKeyQuery, APIKeyHeader
... from auth.schemas import LoginRequest, LoginResponse, LogoutRequest
... from myproject.schemas import UnauthorizedResponse, OkResponse
...
...
... router = Router()
...
...
... @router.post('/login', response={
...     200: LoginResponse,
...     401: UnauthorizedResponse})
... def auth_login(request: HttpRequest, user: LoginRequest):
...     user = authenticate(
...         request=request,
...         username=user.username,
...         password=user.password)
...     if user:
...         login(request, user)
...         return 200, {'session_key': request.session.session_key}
...     else:
...         return 401, {'data': 'Login and/or password are incorrect'}
...
...
... @router.post('/logout', response={
...     200: OkResponse,
...     401: UnauthorizedResponse})
... def auth_logout(request: HttpRequest, data: LogoutRequest):
...     try:
...         Session.objects.get(session_key=data.session_key)
...     except Session.DoesNotExist:
...         return 401, {'data': 'Invalid session key'}
...     else:
...         logout(request)
...         return 200, {'data': 'User logout successful'}
...
...
... class SessionID(APIKeyHeader):
...     param_name = 'X-SESSION-ID'
...
...     def authenticate(self, request, key):
...         try:
...             Session.objects.get(session_key=key)
...         except Session.DoesNotExist:
...             return None
...         else:
...             return True