Skip to main content

Django REST framework authentication package

Project description

VQ-Django-Auth

A robust Django REST framework authentication solution providing ready-to-use endpoints for authentication flows.

Features

  • Authentication APIs: Login, logout, and user information endpoints
  • Password Management: Change password, reset password via email
  • Token Authentication: Built-in token-based authentication support
  • Customizable: Highly configurable serializers, views, and endpoints
  • Simple Integration: Designed to work smoothly with Django and Django REST Framework

Requirements

  • Python 3.8+
  • Django 4.2+ or 5.2+
  • Django REST Framework 3.15+

Installation

pip install vq-django-auth

Or using uv:

uv pip install vq-django-auth

Quick Setup

  1. Add to INSTALLED_APPS:
INSTALLED_APPS = [
    # Django apps
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    # ...

    # Required for Token Authentication
    "rest_framework",
    "rest_framework.authtoken",

    # VQ Django Auth
    "vq_django_auth",
]
  1. Configure authentication method:
from vq_django_auth.choices import AuthMethod

VQ_REST_AUTH = {
    "AUTH_METHOD": AuthMethod.TOKEN,  # Use AuthMethod.SESSION for session-based auth
}
  1. Add to URLs:
from django.urls import path, include

urlpatterns = [
    # ...
    path("api/auth/", include("vq_django_auth.urls")),
    # ...
]
  1. Configure REST Framework settings:
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],
    # ...
}

API Endpoints

Endpoint Method Description
/login/ POST Login and obtain token
/logout/ POST Logout and invalidate token
/user/ GET, PUT, PATCH Retrieve/update user details
/password/change/ POST Change user password
/password/reset/ POST Request password reset email
/password/reset/confirm/ POST Confirm password reset

Login

Request:

{
  "username": "yourusername",
  "password": "yourpassword"
}

Response (200 OK):

{
  "key": "your-auth-token"
}

User Details

Request (with Authorization header):

GET /user/
Authorization: Token your-auth-token

Response (200 OK):

{
  "pk": 1,
  "username": "yourusername",
  "email": "user@example.com",
  "first_name": "First",
  "last_name": "Last"
}

Authentication Methods

Token Authentication

When AUTH_METHOD is set to AuthMethod.TOKEN, the login endpoint returns an authentication token:

from vq_django_auth.choices import AuthMethod

VQ_REST_AUTH = {
    "AUTH_METHOD": AuthMethod.TOKEN,
}

Session Authentication

When AUTH_METHOD is set to AuthMethod.SESSION, login uses Django sessions:

from vq_django_auth.choices import AuthMethod

VQ_REST_AUTH = {
    "AUTH_METHOD": AuthMethod.SESSION,
}

Note: The AUTH_METHOD setting is required and must be set to either AuthMethod.SESSION or AuthMethod.TOKEN.

Configuration

You can customize the behavior by adding a VQ_REST_AUTH dictionary in your Django settings:

from vq_django_auth.choices import AuthMethod

VQ_REST_AUTH = {
    # Custom serializers
    "LOGIN_SERIALIZER": "yourapp.serializers.CustomLoginSerializer",
    "USER_DETAILS_SERIALIZER": "yourapp.serializers.CustomUserDetailsSerializer",

    # Token configuration
    "TOKEN_CREATOR": "yourapp.utils.custom_token_creator",

    # Password reset settings
    "PASSWORD_RESET_USE_SITES_DOMAIN": True,

    # Authentication method (required)
    "AUTH_METHOD": AuthMethod.SESSION,  # or AuthMethod.TOKEN
}

Available Settings

Setting Default Description
AUTH_METHOD None (required) Authentication method: AuthMethod.SESSION or AuthMethod.TOKEN
LOGIN_SERIALIZER "vq_django_auth.serializers.LoginSerializer" Serializer used for login
TOKEN_SERIALIZER "vq_django_auth.serializers.TokenSerializer" Token serializer
USER_DETAILS_SERIALIZER "vq_django_auth.serializers.UserDetailsSerializer" User details serializer
PASSWORD_RESET_SEND_MAIL "vq_django_auth.usecases.password_reset_send_mail" Function to send password reset emails
FRONT_URL_RESET_EMAIL None Base URL for password reset links in emails

Custom Serializers

To create a custom serializer, extend the base serializer and override its methods:

from vq_django_auth.serializers import LoginSerializer

class CustomLoginSerializer(LoginSerializer):
    def validate(self, attrs):
        attrs = super().validate(attrs)
        # Add custom validation here
        return attrs

Customize password reset

Frontend URL for Reset Emails

Use FRONT_URL_RESET_EMAIL to specify the base URL for password reset links. This is useful when your frontend application handles password resets separately from your Django backend:

VQ_REST_AUTH = {
    "FRONT_URL_RESET_EMAIL": "/reset-password",
    # Other settings...
}

The reset email templates will receive this URL in the context as front_url. You can use it to construct the complete reset URL like: {{ front_url }}/{{ uid }}/{{ token }}/

This allows users to be directed to your frontend application where you can then send the verification data to your API endpoint.

Custom Password Reset Email

To customize the password reset email, you can create your own email sending function and configure it in your settings:

# yourapp/email_utils.py
from django.template import loader
from django.core.mail import EmailMultiAlternatives

def custom_password_reset_email(
    context,
    subject_template_name="emails/custom_password_reset_subject.txt",
    email_template_name="emails/custom_password_reset.html",
):
    """
    Send a custom password reset email.

    Args:
        context: Dictionary containing email context variables:
            - email: User's email address
            - domain: Site domain
            - site_name: Name of the site
            - uid: Base64 encoded user ID
            - user: User object
            - front_url: URL fragment from settings
            - token: Password reset token
            - protocol: 'http' or 'https'
        subject_template_name: Path to subject template
        email_template_name: Path to email body template
    """
    subject = loader.render_to_string(subject_template_name, context)
    # Email subject *must not* contain newlines
    subject = "".join(subject.splitlines())
    body = loader.render_to_string(email_template_name, context)

    email_message = EmailMultiAlternatives(
        subject=subject,
        body=body,
        from_email="support@yoursite.com",  # Or use settings.DEFAULT_FROM_EMAIL
        to=[context["email"]],
    )

    # Add HTML content if needed
    # email_message.attach_alternative(html_content, "text/html")

    email_message.send()

Then configure your settings:

VQ_REST_AUTH = {
    "PASSWORD_RESET_SEND_MAIL": "yourapp.email_utils.custom_password_reset_email",
    # Other settings...
}

Development Setup

This project uses uv and tox for development.

# Install dependencies
uv tool install tox --with tox-uv

# Run tests
tox

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

vq_django_auth-0.3.0.tar.gz (64.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

vq_django_auth-0.3.0-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file vq_django_auth-0.3.0.tar.gz.

File metadata

  • Download URL: vq_django_auth-0.3.0.tar.gz
  • Upload date:
  • Size: 64.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for vq_django_auth-0.3.0.tar.gz
Algorithm Hash digest
SHA256 ed8baee02de2b07e5be26fd15dba409c7b735b9eb7f09fc4ec8874bd16ece395
MD5 f0d1eceaa1b309b7b303273a64a3795c
BLAKE2b-256 892351bf744b60179994f460355c044ac01591f03fb16a18c6ec204be47c13c7

See more details on using hashes here.

File details

Details for the file vq_django_auth-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: vq_django_auth-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for vq_django_auth-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 48182cbef8f5710bf57a525f46ee221f833d8b6f75eda90cb7a37a87ca6c6ec3
MD5 78c65d2aca0470b92966e03e4ce38969
BLAKE2b-256 8d9eefda1115b2e8991d4f2ef27c932245918c7ac39ed43f258acebfa1a0ff97

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page