17.7. Ninja Auth

17.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'}}}

17.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

17.7.3. Assignments

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django Ninja Login
# - Difficulty: medium
# - Lines: 24
# - Minutes: 21

# %% English
# 0. Use `myproject.shop`
# 1. Create an endpoint `GET /api/v2/auth/login`
# 2. Endpoint takes `username` and `password`
# 3. If `username` and `password` are invalid, then display error
# 4. If `username` and `password` are valid, then login user
# 5. If user is logged in, then return `request.session.session_key`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz endpoint `GET /api/v2/auth/login`
# 2. Endpoint przyjmuje `username` i `password`
# 3. Jeżeli `username` i `password` są niepoprawne, to wyświetl błąd
# 4. Jeżeli `username` i `password` są poprawne, to zaloguj użytkownika
# 5. Jeżeli użytkownik jest zalogowany, to zwróć `request.session.session_key`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django Ninja SessionAuth
# - Difficulty: easy
# - Lines: 8
# - Minutes: 8

# %% English
# 0. Use `myproject.core`
# 1. Create class `SessionAuth()`
# 2. Class should inherit from `ninja.security.APIKeyHeader`
# 3. Define `param_name = "X-SESSIONID"`
# 4. Define method `authenticate(self, request, sessionid)`
# 5. Method should return `Session` object with given `session_key`
# 6. In case of missing session, or error should return `None`

# %% Polish
# 0. Użyj `myproject.core`
# 1. Stwórz klasę `SessionAuth()`
# 2. Klasa ma dziedziczyć po `ninja.security.APIKeyHeader`
# 3. Zdefiniuj `param_name = "X-SESSIONID"`
# 4. Zdefiniuj metodę `authenticate(self, request, sessionid)`
# 5. Metoda ma zwracać objekt `Session` o podanym `session_key`
# 6. W przypadku braku sesji, lub błędu ma zwracać `None`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django Ninja Logout
# - Difficulty: easy
# - Lines: 8
# - Minutes: 8

# %% English
# 0. Use `myproject.core`
# 1. Create an endpoint `POST /api/v2/auth/login`
# 2. Endpoint should be available only for logged in users
# 3. Endpoint logs-out user
# 4. Endpoint returns `200 OK` and `{"detail": "User logout successful"}`

# %% Polish
# 0. Użyj `myproject.core`
# 1. Stwórz endpoint `POST /api/v2/auth/login`
# 2. Dostęp do endpointu ma być możliwy tylko dla zalogowanych użytkowników
# 3. Endpoint wylogowuje użytkownika
# 4. Endpoint zwraca `200 OK` i `{"detail": "User logout successful"}`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...