### Install Django REST Knox Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/installation.md Use pip to install the django-rest-knox package. Ensure you have Python and pip installed. ```bash pip install django-rest-knox ``` -------------------------------- ### Configure Login, Logout, and LogoutAll URLs Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md Set up URL patterns for Knox's login, logout, and logoutall views. This example demonstrates routing for custom and default views. ```python from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] ``` -------------------------------- ### Login with JSON Credentials (curl) Source: https://context7.com/jazzband/django-rest-knox/llms.txt Example of logging in using JSON credentials with curl. Requires username and password in the request body. ```bash # Login with JSON credentials curl -X POST http://localhost:8000/api/auth/login/ \ -H "Content-Type: application/json" \ -d '{"username": "john_doe", "password": "secretpassword"}' ``` -------------------------------- ### Login with Basic Authentication (curl) Source: https://context7.com/jazzband/django-rest-knox/llms.txt Example of logging in using Basic Authentication with curl. Requires username and password in the Authorization header. ```bash # Login with Basic Authentication curl -X POST http://localhost:8000/api/auth/login/ \ -u "username:password" \ -H "Content-Type: application/json" ``` -------------------------------- ### Example Authorization Header for Token Authentication Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md This is the format for the Authorization header when using TokenAuthentication. Replace the token with a valid one. ```javascript Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345 ``` -------------------------------- ### Custom Login View with Basic Authentication Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md Overwrite Knox's LoginView to use BasicAuthentication alongside TokenAuthentication. This example shows how to set acceptable authentication classes. ```python from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] ``` -------------------------------- ### Configure MkDocs Serve Port Source: https://github.com/jazzband/django-rest-knox/blob/develop/README.md To change the port for the MkDocs development server, set the MKDOCS_DEV_PORT environment variable before running the script. This example sets the port to 8080. ```bash MKDOCS_DEV_PORT="8080" ./mkdocs.sh ``` -------------------------------- ### Access Protected Endpoint with Token Source: https://context7.com/jazzband/django-rest-knox/llms.txt Send a GET request to a protected endpoint, including the token in the Authorization header. A valid token will return the protected data, while an invalid token will result in a 401 Unauthorized response. ```bash # Accessing protected endpoint with token curl -X GET http://localhost:8000/api/protected/ \ -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345" # Response: # { # "message": "Hello, john_doe!", # "token_created": "2024-01-15T10:30:00.000000Z", # "token_expiry": "2024-01-15T20:30:00.000000Z" # } # Invalid token response (401 Unauthorized): # {"detail": "Invalid token."} ``` -------------------------------- ### Configure INSTALLED_APPS and DEFAULT_AUTHENTICATION_CLASSES Source: https://context7.com/jazzband/django-rest-knox/llms.txt Add 'knox' to INSTALLED_APPS and set 'knox.auth.TokenAuthentication' as the default authentication class in settings.py. ```python # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'knox', # ... your apps ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), } ``` -------------------------------- ### Apply Migrations Source: https://context7.com/jazzband/django-rest-knox/llms.txt Run Django migrations to set up the necessary database tables for Knox. ```bash # Apply migrations python manage.py migrate ``` -------------------------------- ### Run MkDocs Serve in Docker Source: https://github.com/jazzband/django-rest-knox/blob/develop/README.md Use this command to serve the documentation locally using MkDocs within a Docker container. The server will be accessible on localhost:8000 by default. ```bash ./mkdocs.sh ``` -------------------------------- ### Build Documentation with MkDocs Source: https://github.com/jazzband/django-rest-knox/blob/develop/README.md Execute MkDocs build commands within the repository using the provided script. This command builds the static documentation files. ```bash ./mkdocs build ``` -------------------------------- ### Configure INSTALLED_APPS Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/installation.md Add 'rest_framework' and 'knox' to your Django project's INSTALLED_APPS setting. Remove 'rest_framework.authtoken' if it was previously used. ```python INSTALLED_APPS = ( ... 'rest_framework', 'knox', ... ) ``` -------------------------------- ### Display MkDocs Help Source: https://github.com/jazzband/django-rest-knox/blob/develop/README.md Access the help information for MkDocs commands by running the script with the --help flag. This displays available commands and options. ```bash ./mkdocs --help ``` -------------------------------- ### Configure Individual Routes with Custom Login View Source: https://context7.com/jazzband/django-rest-knox/llms.txt Optionally, configure individual authentication routes with a custom login view. ```python # Or configure individual routes with custom login view from knox import views as knox_views from yourapp.views import LoginView urlpatterns = [ path('api/auth/login/', LoginView.as_view(), name='knox_login'), path('api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path('api/auth/logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] ``` -------------------------------- ### Optional Knox Configuration Source: https://context7.com/jazzband/django-rest-knox/llms.txt Configure token TTL, hashing algorithm, and other settings in settings.py. These are the default values. ```python # Optional Knox configuration (these are the defaults) from datetime import timedelta REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'AUTO_REFRESH_MAX_TTL': None, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'TOKEN_PREFIX': '', } ``` -------------------------------- ### Apply Django Migrations Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/installation.md Run Django migrations to create the necessary database tables for Knox. This command should be executed from your project's root directory. ```bash python manage.py migrate ``` -------------------------------- ### Login with Username/Password JSON Source: https://context7.com/jazzband/django-rest-knox/llms.txt Create a custom LoginView that accepts username and password via a JSON body. This is useful when Token Authentication is the only authentication class. ```python # views.py from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) ``` -------------------------------- ### Custom Login View with Basic Authentication Source: https://context7.com/jazzband/django-rest-knox/llms.txt Create a custom LoginView that uses Basic Authentication. This view accepts username and password via Basic Auth headers. ```python # Custom login view with Basic Authentication # views.py from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] ``` -------------------------------- ### Reverse URL Lookup Source: https://context7.com/jazzband/django-rest-knox/llms.txt Demonstrates how to reverse lookup URLs for Knox authentication endpoints. ```python # Reverse URL lookup from django.urls import reverse login_url = reverse('knox_login') logout_url = reverse('knox_logout') ``` -------------------------------- ### Programmatic Token Management with AuthToken Model Source: https://context7.com/jazzband/django-rest-knox/llms.txt Manage authentication tokens programmatically using the AuthToken model. This includes creating tokens for users, setting custom expiry, adding prefixes, listing existing tokens, and deleting specific or all tokens for a user. ```python from knox.models import AuthToken, get_token_model from django.contrib.auth import get_user_model User = get_user_model() AuthToken = get_token_model() # Create a token for a user user = User.objects.get(username='john_doe') instance, token = AuthToken.objects.create(user=user) print(f"Token: {token}") # The actual token string to send to client print(f"Expiry: {instance.expiry}") print(f"Created: {instance.created}") # Create token with custom expiry from datetime import timedelta instance, token = AuthToken.objects.create( user=user, expiry=timedelta(days=30) # 30-day token ) # Create token with prefix instance, token = AuthToken.objects.create( user=user, prefix="app1_" ) # List all tokens for a user for auth_token in user.auth_token_set.all(): print(f"Token key: {auth_token.token_key}, Expiry: {auth_token.expiry}") # Delete a specific token auth_token.delete() # Delete all tokens for a user (force logout everywhere) user.auth_token_set.all().delete() ``` -------------------------------- ### Include Knox URLs in Django Project Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/urls.md Include the `knox.urls` configuration in your project's `urlpatterns`. Use the string syntax for the path to avoid import-time errors related to the User model. ```python from django.urls import path, include urlpatterns = [ #...snip... path(r'api/auth/', include('knox.urls')) #...snip... ] ``` -------------------------------- ### Configure Global Token Authentication Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md Set TokenAuthentication as a default for all views by adding it to REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]. If it's the only class, ensure your login view is handled correctly. ```python REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", "knox.auth.TokenAuthentication", ) } ``` -------------------------------- ### LoginView API Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/views.md Handles user authentication and token generation. Accepts POST requests and can be customized through helper methods. ```APIDOC ## POST /api/auth/login ### Description This view handles user authentication. It accepts POST requests and returns a token upon successful authentication. It can be customized by overriding helper methods. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body This endpoint accepts an empty request body by default. Authentication is handled via the request headers based on `DEFAULT_AUTHENTICATION_CLASSES`. ### Request Example (No request body is sent) ### Response #### Success Response (200) - **token** (string) - The authentication token. - **expiry** (string) - The timestamp indicating when the token expires. - **user** (object, optional) - User details if a UserSerializer is configured. #### Response Example ```json { "token": "your_auth_token_here", "expiry": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Configure Token Limit Per User Source: https://context7.com/jazzband/django-rest-knox/llms.txt Set a global limit for active tokens per user in `settings.py` to restrict simultaneous sessions. Exceeding this limit will result in a 403 Forbidden response. ```python # settings.py REST_KNOX = { # Allow only 3 active tokens per user 'TOKEN_LIMIT_PER_USER': 3, } ``` ```bash # When limit is exceeded: curl -X POST http://localhost:8000/api/auth/login/ \ -u "username:password" ``` ```json # Response (HTTP 403): # {"error": "Maximum amount of tokens allowed per user exceeded."} ``` -------------------------------- ### Configure Django REST Knox Settings Source: https://context7.com/jazzband/django-rest-knox/llms.txt Customize token hashing, length, TTL, user serializer, token limits, auto-refresh, and authorization header prefix in `settings.py`. ```python from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' # Or custom: 'yourapp.CustomAuthToken' REST_KNOX = { # Hash algorithm for token storage (sha512, sha3_512, or md5 for testing only) 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', # Length of generated token string 'AUTH_TOKEN_CHARACTER_LENGTH': 64, # Token lifetime (None for never expire) 'TOKEN_TTL': timedelta(hours=10), # Serializer for user data in login response (None to omit user data) 'USER_SERIALIZER': 'knox.serializers.UserSerializer', # Maximum active tokens per user (None for unlimited) 'TOKEN_LIMIT_PER_USER': None, # Extend token expiry on each authenticated request 'AUTO_REFRESH': False, # Maximum token lifetime with auto-refresh 'AUTO_REFRESH_MAX_TTL': None, # Minimum seconds between expiry updates 'MIN_REFRESH_INTERVAL': 60, # Authorization header prefix (e.g., "Token", "Bearer") 'AUTH_HEADER_PREFIX': 'Token', # Datetime format for expiry in responses 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, # Token model path 'TOKEN_MODEL': 'knox.AuthToken', # Prefix prepended to generated tokens 'TOKEN_PREFIX': '', } ``` -------------------------------- ### Include Knox URLs Source: https://context7.com/jazzband/django-rest-knox/llms.txt Include Knox's default URL patterns for authentication endpoints in your project's urls.py. ```python # urls.py from django.urls import path, include urlpatterns = [ path('api/auth/', include('knox.urls')), # Results in: # /api/auth/login/ -> LoginView # /api/auth/logout/ -> LogoutView # /api/auth/logoutall/ -> LogoutAllView ] ``` -------------------------------- ### Configure REST_KNOX Settings Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/settings.md Set these options in your Django settings.py file to customize Knox behavior. Ensure 'KNOX_TOKEN_MODEL' is set if using a custom token model. ```python #...snip... # These are the default values if none are set from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'AUTO_REFRESH_MAX_TTL': None, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, 'TOKEN_MODEL': 'knox.AuthToken', } #...snip... ``` -------------------------------- ### Custom Token Limit Per User in View Source: https://context7.com/jazzband/django-rest-knox/llms.txt Implement `get_token_limit_per_user` in a custom `LoginView` to dynamically set token limits based on user attributes, like premium status. ```python # Custom token limit in view from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): def get_token_limit_per_user(self): # Premium users get more tokens if self.request.user.is_premium: return 10 return 3 ``` -------------------------------- ### Protect API Views with TokenAuthentication Source: https://context7.com/jazzband/django-rest-knox/llms.txt Set TokenAuthentication as the authentication class on your views or viewsets to protect them. Ensure IsAuthenticated permission is also applied. The request.user and request.auth objects will be populated upon successful authentication. ```python from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ProtectedView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): # request.user contains the authenticated Django User # request.auth contains the AuthToken instance return Response({ 'message': f'Hello, {request.user.username}!', 'token_created': request.auth.created, 'token_expiry': request.auth.expiry, }) ``` ```python from rest_framework import viewsets from knox.auth import TokenAuthentication class ItemViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Item.objects.all() serializer_class = ItemSerializer ``` -------------------------------- ### Custom Logout View with Response Source: https://context7.com/jazzband/django-rest-knox/llms.txt Extend Knox's LogoutView to provide a custom response body upon successful logout. This allows for a more user-friendly confirmation message. ```python from knox.views import LogoutView as KnoxLogoutView from rest_framework.response import Response class LogoutView(KnoxLogoutView): def get_post_response(self, request): return Response( {"message": f"Goodbye, {request.user.username}!"}, status=200 ) ``` -------------------------------- ### Custom Login View for Token Generation Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md This custom LoginView allows token generation even when TokenAuthentication is the only default. It explicitly allows any permission and uses AuthTokenSerializer. ```python from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) ``` -------------------------------- ### Configure Token Expiry and Auto-Refresh Source: https://context7.com/jazzband/django-rest-knox/llms.txt Configure token expiration settings in `settings.py`. `TOKEN_TTL` sets the default token lifetime, `AUTO_REFRESH` enables automatic extension of expiry on requests, `AUTO_REFRESH_MAX_TTL` sets the maximum lifetime, and `MIN_REFRESH_INTERVAL` controls the frequency of expiry updates. ```python # settings.py from datetime import timedelta REST_KNOX = { # Token expires 10 hours after creation 'TOKEN_TTL': timedelta(hours=10), # Never expire (use with caution) # 'TOKEN_TTL': None, # Auto-extend token expiry on each request 'AUTO_REFRESH': True, # Maximum total token lifetime (even with auto-refresh) 'AUTO_REFRESH_MAX_TTL': timedelta(days=7), # Minimum seconds between expiry updates (reduces DB writes) 'MIN_REFRESH_INTERVAL': 60, } ``` -------------------------------- ### Handle Knox Token Events with Signals Source: https://context7.com/jazzband/django-rest-knox/llms.txt Utilize Django signals like `user_logged_in`, `user_logged_out`, and `token_expired` to trigger custom actions upon authentication events. Ensure receivers are imported and registered. ```python # signals.py from django.contrib.auth.signals import user_logged_in, user_logged_out from knox.signals import token_expired from django.dispatch import receiver @receiver(user_logged_in) def on_user_logged_in(sender, request, user, **kwargs): # Called when a new token is created via LoginView print(f"User {user.username} logged in from {request.META.get('REMOTE_ADDR')}") # Log to audit trail, send notification, etc. @receiver(user_logged_out) def on_user_logged_out(sender, request, user, **kwargs): # Called when LogoutView or LogoutAllView is used print(f"User {user.username} logged out") @receiver(token_expired) def on_token_expired(sender, username, source, **kwargs): # Called when an expired token is cleaned up during authentication print(f"Token expired for {username} (source: {source})") ``` -------------------------------- ### Custom LoginView with Dynamic Token TTL Source: https://context7.com/jazzband/django-rest-knox/llms.txt Override `get_token_ttl` to provide different token expiry durations based on request data, such as for a 'remember me' feature. ```python from knox.views import LoginView as KnoxLoginView from datetime import timedelta class LoginView(KnoxLoginView): def get_token_ttl(self): # Different expiry for "remember me" functionality if self.request.data.get('remember_me'): return timedelta(days=30) return timedelta(hours=10) ``` -------------------------------- ### Set Default Authentication Class Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/installation.md Configure Django REST framework's DEFAULT_AUTHENTICATION_CLASSES to use Knox's TokenAuthentication. This is typically done in your settings.py file. ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), ... } ``` -------------------------------- ### Custom User Serializer for Login Responses Source: https://context7.com/jazzband/django-rest-knox/llms.txt Define a custom `serializers.ModelSerializer` and configure `REST_KNOX['USER_SERIALIZER']` in `settings.py` to control the user data included in login responses. ```python # serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model User = get_user_model() class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'is_staff') ``` ```python # settings.py REST_KNOX = { 'USER_SERIALIZER': 'yourapp.serializers.CustomUserSerializer', } ``` ```json # Login response with custom serializer: # { # "expiry": "2024-01-15T20:30:00.000000Z", # "token": "abc123...", # "user": { # "id": 1, # "username": "john_doe", # "email": "john@example.com", # "first_name": "John", # "last_name": "Doe", # "is_staff": false # } # } ``` -------------------------------- ### Implement Token Authentication in a DRF View Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/auth.md Add TokenAuthentication to your APIView or ViewSet to secure endpoints. Ensure the Authorization header is set correctly in requests. ```python from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ExampleView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) ``` -------------------------------- ### Extend AuthToken Model for Custom Fields Source: https://context7.com/jazzband/django-rest-knox/llms.txt Subclass `knox.models.AbstractAuthToken` to add custom fields like `device_name`, `ip_address`, and `user_agent`. Update `settings.py` with `KNOX_TOKEN_MODEL` and `REST_KNOX['TOKEN_MODEL']` to use your custom model. Override `create_token` in your `LoginView` to populate these fields. ```python # models.py from knox.models import AbstractAuthToken class CustomAuthToken(AbstractAuthToken): device_name = models.CharField(max_length=255, blank=True) ip_address = models.GenericIPAddressField(null=True, blank=True) user_agent = models.TextField(blank=True) class Meta: swappable = 'KNOX_TOKEN_MODEL' ``` ```python # settings.py KNOX_TOKEN_MODEL = 'yourapp.CustomAuthToken' REST_KNOX = { 'TOKEN_MODEL': 'yourapp.CustomAuthToken', } ``` ```python # views.py - Custom login to populate extra fields from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): def create_token(self): from yourapp.models import CustomAuthToken return CustomAuthToken.objects.create( user=self.request.user, expiry=self.get_token_ttl(), prefix=self.get_token_prefix(), device_name=self.request.data.get('device_name', ''), ip_address=self.request.META.get('REMOTE_ADDR'), user_agent=self.request.META.get('HTTP_USER_AGENT', ''), ) ``` -------------------------------- ### Customize LoginView Response Payload Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/views.md Override `get_post_response_data` to customize the JSON payload returned upon successful login. This method allows inclusion of user details and formatted expiry times. ```python def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token } if UserSerializer is not None: data["user"] = UserSerializer( request.user, context=self.get_context() ).data return data ``` -------------------------------- ### Customize LogoutView Response Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/views.md Override `get_post_response` in `LogoutView` to customize the response body and status code for a successful logout. This allows for custom messages or different HTTP status codes. ```python def get_post_response(self, request): return Response({"bye-bye": request.user.username}, status=200) ``` -------------------------------- ### Access Knox Constants Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/settings.md Use these constants for information about token digest length and maximum prefix length. These values should not be modified. ```python from knox.settings import CONSTANTS print(CONSTANTS.DIGEST_LENGTH) #=> 128 ``` -------------------------------- ### All Sessions Logout Source: https://context7.com/jazzband/django-rest-knox/llms.txt Utilize the LogoutAllView to invalidate all tokens associated with the authenticated user, forcing a logout from all devices and sessions. This operation returns an HTTP 204 No Content status. ```bash # Logout from all sessions curl -X POST http://localhost:8000/api/auth/logoutall/ \ -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345" # Response: HTTP 204 No Content # All tokens for this user are now invalid ``` -------------------------------- ### Single Session Logout Source: https://context7.com/jazzband/django-rest-knox/llms.txt Use the LogoutView to invalidate the token used in the request, logging out the current session. Other tokens for the same user remain active. A successful logout returns an HTTP 204 No Content status. ```bash # Logout current session curl -X POST http://localhost:8000/api/auth/logout/ \ -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345" # Response: HTTP 204 No Content # Using the same token again will fail: # {"detail": "Invalid token."} ``` -------------------------------- ### Reverse Knox URL Names Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/urls.md You can reverse the names of the default Knox views using Django's `reverse` function. This is useful for generating URLs in your code. ```python from django.urls import reverse reverse('knox_login') reverse('knox_logout') reverse('knox_logoutall') ``` -------------------------------- ### LogoutView API Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/views.md Handles the logout of a user by invalidating their current token. Accepts POST requests. ```APIDOC ## POST /api/auth/logout ### Description This view invalidates the token used for authentication, effectively logging the user out. It responds to Knox Token Authentication. ### Method POST ### Endpoint /api/auth/logout ### Parameters #### Request Body This endpoint accepts an empty request body. ### Request Example (No request body is sent) ### Response #### Success Response (204) By default, a HTTP 204 No Content response is returned on successful logout. This can be customized by overriding the `get_post_response` method. #### Response Example (Customized) ```json { "bye-bye": "username" } ``` ``` -------------------------------- ### LogoutAllView API Source: https://github.com/jazzband/django-rest-knox/blob/develop/docs/views.md Handles the logout of a user by invalidating all their existing tokens. Accepts POST requests. ```APIDOC ## POST /api/auth/logout/all ### Description This view invalidates the token used for authentication, as well as all other tokens associated with the same user account. It responds to Knox Token Authentication. ### Method POST ### Endpoint /api/auth/logout/all ### Parameters #### Request Body This endpoint accepts an empty request body. ### Request Example (No request body is sent) ### Response #### Success Response (204) By default, a HTTP 204 No Content response is returned on successful logout. This can be customized by overriding the `get_post_response` method. #### Response Example (Customized) ```json { "message": "All tokens invalidated." } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.