### Run Demo Server Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Commands to navigate to the example directory, install dependencies, migrate the database, and run the development server for the demo. ```shell cd example pip install -r requirements.txt python manage.py migrate python manage.py runserver ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to set up the development environment by installing necessary dependencies. ```make make install ``` -------------------------------- ### Install New Package Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/migrating.md Use this command to install the renamed package. ```bash pip install drf-simple-apikey ``` -------------------------------- ### Run Development Server Source: https://github.com/koladev32/drf-simple-apikey/blob/main/drf-docs/README.md Commands to start the Next.js development server using npm, pnpm, or yarn. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Install bump2version Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/development_and_contributing.md Install the bump2version package using pip. This tool is used for managing version numbers across the project. ```bash pip install bump2version ``` -------------------------------- ### Start API Key Rotation using Management Command Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/rotation.md Use this Django management command to initiate the API key rotation process. This command creates a rotation object and enables the rotation flag in the database. ```shell python manage.py rotation ``` -------------------------------- ### Bump minor version Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/development_and_contributing.md Use this command to increment the minor version number. For example, 2.2.1 would become 2.3.0. ```bash bump2version minor ``` -------------------------------- ### Bump major version Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/development_and_contributing.md Use this command to increment the major version number. For example, 2.2.1 would become 3.0.0. ```bash bump2version major ``` -------------------------------- ### Bump patch version Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/development_and_contributing.md Use this command to increment the patch version number. For example, 2.2.1 would become 2.2.2. ```bash bump2version patch ``` -------------------------------- ### Run Rotation Migration Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/rotation.md Execute the migrate command to set up the necessary database tables for API key rotation. ```shell python manage.py migrate drf-simple-apikey_rotation ``` -------------------------------- ### Run Tests Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to execute all project tests to ensure changes have not introduced regressions. ```make make test ``` -------------------------------- ### Clone Project Repository Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to clone the drf-simple-apikey project repository from GitHub to set up the development environment. ```bash git clone https://github.com/koladev32/drf-simple-apikey.git ``` -------------------------------- ### Run Database Migrations for Analytics Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/analytics.md Execute the Django migrate command to create the necessary database tables for storing API key analytics data. ```shell python manage.py migrate drf-simple-apikey_analytics ``` -------------------------------- ### Run Database Migrations Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to apply database migrations, typically used when changes include database schema modifications. ```make make migrations ``` -------------------------------- ### Register drf-simple-apikey in settings.py Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/getting_started.md Add 'drf_simple_apikey' to your INSTALLED_APPS in settings.py. ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "drf_simple_apikey", ] ``` -------------------------------- ### Generate Migrations Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/customizing_api_key_model.md After defining your custom API key model, run Django's `makemigrations` command to generate the necessary migration files for your new table. ```bash python manage.py makemigrations ``` -------------------------------- ### Check Code and Migrations Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to validate changes against project checks, including code and database migrations. ```make make check ``` -------------------------------- ### Configure INSTALLED_APPS Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Register the 'drf_simple_apikey' app in your Django project's settings.py file to enable its functionality. ```python INSTALLED_APPS = [ # ... "rest_framework", "drf_simple_apikey", ] ``` -------------------------------- ### Format Code Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md Command to format the code according to project standards before submitting changes. ```make make format ``` -------------------------------- ### Apply Migrations Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/customizing_api_key_model.md Apply the generated migrations to your database to create the new table for your custom API key model. ```bash python manage.py migrate ``` -------------------------------- ### Push Commits and Tags Source: https://github.com/koladev32/drf-simple-apikey/blob/main/CONTRIBUTING.md After bumping the version, push both the new commits and tags to the remote repository. ```bash git push && git push --tags ``` -------------------------------- ### Uninstall Old Package Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/migrating.md Use this command to remove the previous version of the package. ```bash pip uninstall djangorestframework-simple-apikey ``` -------------------------------- ### Apply APIKeyAuthentication to a ViewSet Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/getting_started.md Use APIKeyAuthentication and set the appropriate HTTP methods for your view. ```python from rest_framework import viewsets from drf_simple_apikey.backends import APIKeyAuthentication from rest_framework.response import Response class FruitViewSets(viewsets.ViewSet): http_method_names = ["get"] authentication_classes = (APIKeyAuthentication, ) def list(self, request): return Response([{"detail": True}], 200 ) ``` -------------------------------- ### Configure Custom API Key Model Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Set the fully qualified path to a custom API key model if you have created one. This is primarily used by the analytics addon. ```python DRF_API_KEY = { "API_KEY_CLASS": "myapp.models.CustomAPIKey", # Use custom model } ``` -------------------------------- ### Configure DRF_API_KEY with FERNET_SECRET Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/getting_started.md Set up the DRF_API_KEY dictionary in settings.py and include your generated FERNET_SECRET. ```python DRF_API_KEY = { "FERNET_SECRET": "sVjomf7FFy351xRxDeJWFJAZaE2tG3MTuUv92TLFfOA=" } ``` -------------------------------- ### Configure Input Sanitization Limits Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/security.md Set limits for tracking API usage in analytics, such as the maximum number of unique endpoints per key and the maximum length of an endpoint path. ```python DRF_API_KEY = { "MAX_ENDPOINTS_PER_KEY": 1000, # Maximum unique endpoints to track "MAX_ENDPOINT_LENGTH": 500, # Maximum endpoint path length } ``` -------------------------------- ### Generate a Fernet Key Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/getting_started.md Use the custom Django command to generate a secure Fernet key for your API. ```bash python manage.py generate_fernet_key ``` -------------------------------- ### Add Rotation App to INSTALLED_APPS Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/rotation.md Ensure the rotation app is included in your Django project's INSTALLED_APPS setting. ```python INSTALLED_APPS=( ... "rest_framework", "drf_simple_apikey", "drf_simple_apikey.rotation", # added app ) ``` -------------------------------- ### Enable Audit Logging Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Set ENABLE_AUDIT_LOGGING to True to log security events such as authentication attempts and API key management actions. This aids in security monitoring. ```python DRF_API_KEY = { "ENABLE_AUDIT_LOGGING": True, # Log security events } ``` -------------------------------- ### Add Analytics App to INSTALLED_APPS Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/analytics.md Ensure the drf-simple-apikey.analytics app is included in your Django project's INSTALLED_APPS setting to enable analytics functionality. ```python INSTALLED_APPS = ( ... "rest_framework", "drf_simple_apikey", "drf_simple_apikey.analytics", # Ensure this app is added ) ``` -------------------------------- ### Enforce HTTPS Connections Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Set ENFORCE_HTTPS to True to reject API key requests made over unencrypted HTTP in production environments. This is crucial for security. ```python DRF_API_KEY = { "ENFORCE_HTTPS": True, # Reject HTTP requests in production } ``` -------------------------------- ### Bump Version with bump2version Source: https://github.com/koladev32/drf-simple-apikey/blob/main/CONTRIBUTING.md Use bump2version to manage version numbers for bug fixes, new features, or breaking changes. Ensure commits and tags are pushed after bumping. ```bash bump2version patch # for bug fixes (2.3.0 → 2.3.1) ``` ```bash bump2version minor # for new features (2.3.0 → 2.4.0) ``` ```bash bump2version major # for breaking changes (2.3.0 → 3.0.0) ``` -------------------------------- ### Limit Endpoints Per Key Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Configure MAX_ENDPOINTS_PER_KEY to limit the number of unique endpoints tracked per API key, helping to manage database size and prevent abuse. ```python DRF_API_KEY = { "MAX_ENDPOINTS_PER_KEY": 1000, # Limit tracked endpoints } ``` -------------------------------- ### Configure Django Audit Logging Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/security.md Configure Django's logging settings to capture security events from drf-simple-apikey. Ensure the logger level is set to 'INFO' or lower to capture relevant events. ```python LOGGING = { 'version': 1, 'handlers': { 'file': { 'class': 'logging.FileHandler', 'filename': 'security.log', }, }, 'loggers': { 'drf_simple_apikey': { 'handlers': ['file'], 'level': 'INFO', }, }, } ``` -------------------------------- ### Migrate Django Settings Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/migrating.md Update your Django settings by renaming SIMPLE_API_KEY to DRF_API_KEY. ```python DRF_API_KEY = { 'API_KEY': 'your-api-key-here', 'OTHER_SETTINGS': 'values' } ``` -------------------------------- ### IsActiveEntity Permission Class Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/permissions.md Use this permission class to ensure only active entities have permission to read or write resources. It checks the `is_active` attribute of the request user. ```python class IsActiveEntity(BasePermission): """ A base permission that only checks if the entity (by default, the Django user) is active or not. """ message = "Entity is not active." def has_permission(self, request: HttpRequest, view: typing.Any) -> bool: return request.user.is_active def has_object_permission( self, request: HttpRequest, view: typing.Any, obj ) -> bool: return request.user.is_active ``` -------------------------------- ### Implement APIKeyAuthentication in a ViewSet Source: https://github.com/koladev32/drf-simple-apikey/blob/main/README.md In your Django REST Framework views, specify APIKeyAuthentication as the authentication class and optionally set the permission class. This enables API key authentication for your endpoints. ```python from rest_framework import viewsets from drf_simple_apikey.backends import APIKeyAuthentication from rest_framework.response import Response class FruitViewSets(viewsets.ViewSet): http_method_names = ["get"] authentication_classes = (APIKeyAuthentication,) def list(self, request): return Response([{"detail": True}], 200) ``` -------------------------------- ### Applying IsActiveEntity Permission in a ViewSet Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/permissions.md Integrate the `IsActiveEntity` permission into your Django REST framework ViewSet by setting the `permission_classes` attribute. Ensure `APIKeyAuthentication` is also configured. ```python from drf_simple_apikey.permissions import IsActiveEntity class YourViewSet(viewsets.ViewSet): ... authentication_classes = (APIKeyAuthentication, ) permission_classes = (IsActiveEntity, ) ``` -------------------------------- ### Configure Ignored Routes for Analytics Source: https://github.com/koladev32/drf-simple-apikey/blob/main/drf-docs/content/docs/settings.mdx Specify a list of URL paths that the API Key Analytics Middleware should ignore. Requests to these routes will not be tracked in analytics. The default is `["/admin/"]`. ```python DRF_API_KEY = { "IGNORED_ROUTES": [ "/admin/", # Excludes admin panel routes from analytics "/api/documents/", # Excludes document API routes from analytics "/health/", # Excludes health check endpoints from analytics ] } ``` -------------------------------- ### Configure API Key Rotation Period Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Set the ROTATION_PERIOD to define how long key rotation remains active. After this period, manual swapping of secrets is required. ```python from datetime import timedelta DRF_API_KEY = { "ROTATION_PERIOD": timedelta(days=7), # Rotation active for 7 days } ``` -------------------------------- ### Define Custom APIKey Model Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/customizing_api_key_model.md Define a custom API key model by inheriting from `AbstractAPIKey` and linking it to your custom entity, such as `Organization`. This allows associating API keys with specific instances of your models. ```python from django.db import models from drf_simple_apikey.models import AbstractAPIKey class Organization(models.Model): name = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) class OrganizationAPIKey(AbstractAPIKey): entity = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys", ) ``` -------------------------------- ### Add ApiKeyAnalyticsMiddleware to MIDDLEWARE Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/analytics.md Integrate the ApiKeyAnalyticsMiddleware into your Django project's MIDDLEWARE setting to activate request interception and logging. ```python MIDDLEWARE = [ ... 'django.middleware.security.SecurityMiddleware', 'drf_simple_apikey.analytics.middleware.ApiKeyAnalyticsMiddleware', # Add the middleware here ... ] ``` -------------------------------- ### Configure IP Address Header Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Specify the HTTP header used to extract the client's IP address, particularly when behind a proxy. Defaults to 'REMOTE_ADDR'. ```python DRF_API_KEY = { "IP_ADDRESS_HEADER": "HTTP_X_FORWARDED_FOR", # Use X-Forwarded-For header } ``` -------------------------------- ### Update Import Statements Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/migrating.md Change your Python import statements to reflect the new package name. ```python import drf_simple_apikey ``` -------------------------------- ### Configure Ignored Routes for Analytics Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Specify routes in IGNORED_ROUTES that should be excluded from API Key Analytics Middleware tracking. This prevents usage of certain paths from being logged. ```python DRF_API_KEY = { : “IGNORED_ROUTES”: : “/admin/”, # Excludes admin panel routes from analytics “/api/documents/”, # Excludes document API routes from analytics “/health/”, # Excludes health check endpoints from analytics
] } ``` -------------------------------- ### Stop API Key Rotation using Management Command Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/rotation.md Execute this command to disable the API key rotation process. It sets the is_rotation_enabled flag to False for the latest rotation object. ```shell python manage.py rotation --stop ``` -------------------------------- ### Use APIKeyAuthentication in a ViewSet Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/authentication.md Add the `APIKeyAuthentication` class to the `authentication_classes` attribute of your Django REST Framework ViewSet to enable API key authentication. ```python class YourViewSet(viewsets.ViewSet): http_method_names = ["get"] authentication_classes = (APIKeyAuthentication, ) ... ``` -------------------------------- ### Configure HTTPS Enforcement Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/security.md Explicitly set HTTPS enforcement in your Django settings. By default, it follows the DEBUG setting, enforcing HTTPS in production and allowing HTTP in development. ```python DRF_API_KEY = { "ENFORCE_HTTPS": True, # Explicitly enable (or None to auto-detect from DEBUG) } ``` -------------------------------- ### IsActiveEntity Permission Class Source: https://github.com/koladev32/drf-simple-apikey/blob/main/drf-docs/content/docs/permissions.mdx A custom permission class that checks if the requesting user is active. It implements `has_permission` and `has_object_permission` methods. ```python class IsActiveEntity(BasePermission): """ A base permission that only checks if the entity (by default, the Django user) is active or not. """ message = "Entity is not active." def has_permission(self, request: HttpRequest, view: typing.Any) -> bool: return request.user.is_active def has_object_permission( self, request: HttpRequest, view: typing.Any, obj ) -> bool: return request.user.is_active ``` -------------------------------- ### Default DRF_API_KEY Settings Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Configure default settings for DRF_API_KEY in your Django project's settings.py. Ensure FERNET_SECRET is set for encryption. ```python # Django project settings.py ... DRF_API_KEY = { "FERNET_SECRET": "", "API_KEY_LIFETIME": 365, "AUTHENTICATION_KEYWORD_HEADER": "Api-Key", "ROTATION_PERIOD": timedelta(days=7), "ROTATION_FERNET_SECRET": "", "IGNORED_ROUTES": ["/admin/"] # Routes that should be ignored by API key authentication } ``` -------------------------------- ### Customize Authentication Header Keyword Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/authentication.md Modify the `AUTHENTICATION_KEYWORD_HEADER` in your Django project's `settings.py` to change the expected keyword in the `Authorization` header. ```python DRF_API_KEY = { ... "AUTHENTICATION_KEYWORD_HEADER": "YOUR_CUSTOM_VALUE", } ``` -------------------------------- ### Limit Endpoint Path Length Source: https://github.com/koladev32/drf-simple-apikey/blob/main/docs/settings.md Set MAX_ENDPOINT_LENGTH to restrict the maximum length of endpoint paths stored in analytics, preventing issues caused by excessively long paths. ```python DRF_API_KEY = { "MAX_ENDPOINT_LENGTH": 500, # Maximum endpoint path length } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.