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.5.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.5.0-py3-none-any.whl (20.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: vq_django_auth-0.5.0.tar.gz
  • Upload date:
  • Size: 64.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","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.5.0.tar.gz
Algorithm Hash digest
SHA256 5e37cd1504c28c822a3eb6179fa2acffca1dfda0b0e47ee1fa34c3edc70b639f
MD5 f9484b2e7577e475522513234757362a
BLAKE2b-256 5de7162d2025fa6020507600145bbf2d71ecd135340ad465b5501184480a8a4b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: vq_django_auth-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 20.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","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.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6f10b0dba2319bd195da387ecd2acc915e8f595d54197af8c9eafd3d78f6e9a2
MD5 42e65bb8a8b4ab8583ed328eaaba46a1
BLAKE2b-256 1c896960803fa2ebf6a361de2893ed5011530ad107eff56874e066f65797f857

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