duck.contrib.auth.helpers¶
Duck auth helpers — login, logout, and authenticate.
Supports two backends:
"session": stores user identity inrequest.SESSION(default)."jwt": reads/writes identity fromrequest.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 version of |
|
Async version of |
|
Async version of |
|
Async version of |
|
Asynchronously returns the user ID from a supported backend. |
|
Asynchronously log in an authenticated user using the configured authentication backend. |
|
Async version of |
|
Verify credentials against the User model and return the user if valid. |
|
Resolve the currently authenticated user. |
|
Resolve the currently authenticated user from the JWT store. |
|
Resolve the currently logged-in user from the session. |
|
Returns the user ID from a supported backend. |
|
Log in an authenticated user using the configured authentication backend. |
|
Clear the current user’s auth state from the request. |
|
Set the process-wide default authentication backend. |
Data¶
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_asyncso 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(request: Any, backend: str | None = None) Any | None[source]¶
Async version of
get_user.Resolves the currently authenticated user using the selected authentication backend without blocking the event loop.
- Parameters:
request – The Duck request object.
backend – Authentication backend to use. Supported values are
"session"and"jwt". Defaults toDEFAULT_AUTH_BACKEND.
- Returns:
The authenticated User instance if a valid identity exists, otherwise
None.- Raises:
ValueError – Propagated from
get_userif an unsupported backend name is provided.
… rubric:: Example
user = await async_get_user(request) if user: print(f"Logged in as {user}")
- 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_get_user_id(request, backend: str | None = None)[source]¶
Asynchronously returns the user ID from a supported backend.
- 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
useroruser_idmust be provided, but not both. Whenuseris provided, itspkattribute is used as the authenticated identity. Whenuser_idis provided, it is used directly, which is useful for fast logins where the user identity is already known.For the
sessionbackend, the user ID and backend name are stored inrequest.SESSION. For thejwtbackend, the same values are stored inrequest.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 toDEFAULT_AUTH_BACKEND.
- Raises:
AuthenticationError – If neither
usernoruser_idis provided, if both are provided, ifuserhas no validpk, or ifuser_idis 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 byset_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 islogin’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(request: Any, backend: str | None = None) Any | None[source]¶
Resolve the currently authenticated user.
The user identity is read from the selected authentication backend and resolved against the configured Django User model.
- Parameters:
request – The Duck request object.
backend – Authentication backend to use. Supported values are
"session"and"jwt". Defaults toDEFAULT_AUTH_BACKEND.
- Returns:
The authenticated User instance if a valid identity exists, otherwise
None.- Raises:
ValueError – If an unsupported backend name is provided.
… rubric:: Example
user = get_user(request) if user: print(f"Logged in as {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
loginfromrequest.JWT. ReturnsNoneif 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
useroruser_idmust be provided, but not both. Whenuseris provided, itspkattribute is used as the authenticated identity. Whenuser_idis provided, it is used directly, which is useful for fast logins where the user identity is already known.For the
sessionbackend, the user ID and backend name are stored inrequest.SESSION. For thejwtbackend, the same values are stored inrequest.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 toDEFAULT_AUTH_BACKEND.
- Raises:
AuthenticationError – If neither
usernoruser_idis provided, if both are provided, ifuserhas no validpk, or ifuser_idis 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 byset_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 explicitbackendargument 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")