Users - Authentication Backends

Location: api/nextango/apps/users/backends.py Last Updated: 2026-07-08

Overview

Provides a custom DRF token authentication backend that integrates with the platform's User model. The backend extends Django REST Framework's TokenAuthentication to enforce user.status == 'active' before granting access and logs all authentication outcomes for auditing.


Backend Reference

CustomTokenAuthentication

Extends: rest_framework.authentication.TokenAuthentication

Purpose: Replaces DRF's default TokenAuthentication to add user status validation. A valid token belonging to an inactive user is rejected at the authentication layer rather than requiring each view to check user.status.


authenticate_credentials(key)

Overrides the DRF base method to:

  1. Fetch the Token record (with select_related('user')) for the given key
  2. Reject the request if the token does not exist
  3. Reject the request if token.user.status != 'active'
  4. Return (user, token) on success
ParameterTypePurpose
keystrThe raw token string extracted from the Authorization: Token <key> header

Returns: (User, Token) tuple if credentials are valid, None otherwise.

Logic:

  1. Call Token.objects.select_related('user').get(key=key), which raises Token.DoesNotExist on miss
  2. If Token.DoesNotExist: log a warning with the first 8 characters of the key; return None
  3. If token.user.status != 'active': log a warning with the user's email; return None
  4. Log a success message with the user's email; return (token.user, token)

Django Settings Reference

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'nextango.apps.users.backends.CustomTokenAuthentication',
    ],
}

Usage Notes

  • Status check: The backend rejects any user whose status field is not 'active'. Suspended or deactivated users cannot authenticate even with a valid token.
  • Logging: Authentication failures log at WARNING level; successes log at INFO level. Both include identifying information (email or partial token) to assist with audit and incident response.
  • Token lifecycle: Token creation and rotation are handled by the web_auth domain; see Web Auth Views.

Was this page helpful?