duck.contrib.auth.helpers

Duck auth helpers — login, logout, and authenticate.

Supports two backends:

  • "session": stores user identity in request.SESSION (default).

  • "jwt": reads/writes identity from request.JWT.

Usage:

from duck.contrib.auth import login, logout, authenticate
from duck.contrib.auth.exceptions import AuthenticationError

# Sync
try:
    user = authenticate(request, "brian@example.com", "secret")
except AuthenticationError:
    user = None

if user:
    login(request, user)

# Async
try:
    user = await async_authenticate(request, "brian@example.com", "secret")
except AuthenticationError:
    user = None

if user:
    await async_login(request, user)

Notes:

  • These helpers only support Django models via get_user_model().

  • Set a process-wide default backend with set_default_auth_backend().

Module Contents

Functions

async_authenticate

Async version of authenticate.

async_get_user_from_jwt

Async version of get_user_from_jwt.

async_get_user_from_session

Async version of get_user_from_session.

async_login

Asynchronously log in an authenticated user using the configured authentication backend.

async_logout

Async version of logout.

authenticate

Verify credentials against the User model and return the user if valid.

get_user_from_jwt

Resolve the currently authenticated user from the JWT store.

get_user_from_session

Resolve the currently logged-in user from the session.

get_user_id

Returns the user ID from a supported backend.

login

Log in an authenticated user using the configured authentication backend.

logout

Clear the current user’s auth state from the request.

set_default_auth_backend

Set the process-wide default authentication backend.

Data

BACKEND_KEY

DEFAULT_AUTH_BACKEND

SUPPORTED_BACKENDS

USER_ID_KEY

API

duck.contrib.auth.helpers.BACKEND_KEY

‘_auth_backend’

duck.contrib.auth.helpers.DEFAULT_AUTH_BACKEND

‘session’

duck.contrib.auth.helpers.SUPPORTED_BACKENDS

(‘session’, ‘jwt’)

duck.contrib.auth.helpers.USER_ID_KEY

‘_auth_user_id’

async duck.contrib.auth.helpers.async_authenticate(request: Any, username: str, password: str) Any[source]

Async version of authenticate.

Wraps the sync ORM calls via ensure_async so the event loop is never blocked.

Parameters:
  • request – The Duck request object.

  • username – The username or email to look up.

  • password – The plain-text password to verify.

Returns:

The matching User instance on success.

Raises:

AuthenticationError – Propagated from authenticate.

async duck.contrib.auth.helpers.async_get_user_from_jwt(request: Any) Any | None[source]

Async version of get_user_from_jwt.

Parameters:

request – The Duck request object.

Returns:

The User instance if a valid JWT entry exists, otherwise None.

async duck.contrib.auth.helpers.async_get_user_from_session(request: Any) Any | None[source]

Async version of get_user_from_session.

Parameters:

request – The Duck request object.

Returns:

The User instance if a valid session exists, otherwise None.

async duck.contrib.auth.helpers.async_login(request: Any, user: Any | None = None, user_id: str | int | None = None, backend: str | None = None) None[source]

Asynchronously log in an authenticated user using the configured authentication backend.

Either user or user_id must be provided, but not both. When user is provided, its pk attribute is used as the authenticated identity. When user_id is provided, it is used directly, which is useful for fast logins where the user identity is already known.

For the session backend, the user ID and backend name are stored in request.SESSION. For the jwt backend, the same values are stored in request.JWT.

Parameters:
  • request – The Duck request object.

  • user – Authenticated user instance returned by authenticate.

  • user_id – Authenticated user’s unique ID.

  • backend – Authentication backend to use. Supported values are "session" and "jwt". Defaults to DEFAULT_AUTH_BACKEND.

Raises:
  • AuthenticationError – If neither user nor user_id is provided, if both are provided, if user has no valid pk, or if user_id is invalid.

  • ValueError – If an unsupported backend name is provided.

Example 1:

user = authenticate(request, "brian@example.com", "secret")
login(request, user=user)

Example 2:

user_id = 1 # If user id is already known.
login(request, user_id=user_id)
async duck.contrib.auth.helpers.async_logout(request: Any, backend: str | None = None) None[source]

Async version of logout.

Parameters:
  • request – The Duck request object.

  • backend – Either "session" or "jwt". Defaults to the value set by set_default_auth_backend() (initially "session").

Raises:

ValueError – Propagated from logout.

duck.contrib.auth.helpers.authenticate(request: Any, username: str, password: str) Any[source]

Verify credentials against the User model and return the user if valid.

Looks up the user by the model’s USERNAME_FIELD, then verifies the password using Django’s hasher. Does not touch the session or any auth state — that is login’s responsibility.

Parameters:
  • request – The Duck request object.

  • username – The username or email to look up.

  • password – The plain-text password to verify.

Returns:

The matching User instance on success.

Raises:

AuthenticationError – If the user does not exist, is inactive, or the password does not match.

Example:

user = authenticate(request, "brian@example.com", "secret")
login(request, user)
duck.contrib.auth.helpers.get_user_from_jwt(request: Any) Any | None[source]

Resolve the currently authenticated user from the JWT store.

Reads the user id written by login from request.JWT. Returns None if the entry is absent or the referenced user no longer exists.

Parameters:

request – The Duck request object.

Returns:

The User instance if a valid JWT entry exists, otherwise None.

Example:

user = get_user_from_jwt(request)

if user:
    print(f"JWT user: {user}")
duck.contrib.auth.helpers.get_user_from_session(request: Any) Any | None[source]

Resolve the currently logged-in user from the session.

Parameters:

request – The Duck request object.

Returns:

The User instance if a valid session entry exists, otherwise None.

Example:

user = get_user_from_session(request)

if user:
    print(f"Logged in as {user}")
```
duck.contrib.auth.helpers.get_user_id(request, backend: str | None = None)[source]

Returns the user ID from a supported backend.

duck.contrib.auth.helpers.login(request: Any, user: Any | None = None, user_id: str | int | None = None, backend: str | None = None) None[source]

Log in an authenticated user using the configured authentication backend.

Either user or user_id must be provided, but not both. When user is provided, its pk attribute is used as the authenticated identity. When user_id is provided, it is used directly, which is useful for fast logins where the user identity is already known.

For the session backend, the user ID and backend name are stored in request.SESSION. For the jwt backend, the same values are stored in request.JWT.

Parameters:
  • request – The Duck request object.

  • user – Authenticated user instance returned by authenticate.

  • user_id – Authenticated user’s unique ID.

  • backend – Authentication backend to use. Supported values are "session" and "jwt". Defaults to DEFAULT_AUTH_BACKEND.

Raises:
  • AuthenticationError – If neither user nor user_id is provided, if both are provided, if user has no valid pk, or if user_id is invalid.

  • ValueError – If an unsupported backend name is provided.

Example 1:

user = authenticate(request, "brian@example.com", "secret")
login(request, user=user)

Example 2:

user_id = 1 # If user id is already known.
login(request, user_id=user_id)
duck.contrib.auth.helpers.logout(request: Any, backend: str | None = None) None[source]

Clear the current user’s auth state from the request.

For the session backend the entire session is flushed. For the JWT backend the JWT store is cleared. JWT is stateless, so token invalidation on the client side (discarding the token) is still the caller’s responsibility.

Parameters:
  • request – The Duck request object.

  • backend – Either "session" or "jwt". Defaults to the value set by set_default_auth_backend() (initially "session").

Raises:

ValueError – If an unsupported backend name is given.

Example:

logout(request)
duck.contrib.auth.helpers.set_default_auth_backend(backend: str) None[source]

Set the process-wide default authentication backend.

This affects all subsequent calls to login, logout, and their async equivalents when no explicit backend argument is passed.

Parameters:

backend – Either "session" or "jwt".

Raises:

ValueError – If the given backend is not a supported identifier.

Example:

from duck.contrib.auth import set_default_auth_backend

set_default_auth_backend("jwt")