Utils - Request

smarter.common.utils.request

Helpers for request authentication detection in Django and DRF.

This module provides the is_authenticated_request function, which determines whether a given request object is authenticated. It supports Django’s HttpRequest, Django REST Framework’s Request, and ASGIRequest types, and provides extensive logging for debugging and auditing purposes.

Example usage:

from smarter.common.utils import is_authenticated_request
from django.http import HttpRequest

request = HttpRequest()
request.user = SomeUserObject()
authenticated = is_authenticated_request(request)
print(authenticated)  # True or False depending on user.is_authenticated
smarter.common.utils.request.is_authenticated_request(request)[source]

Determines whether the provided request is authenticated. Provides extensive logging for debugging purposes.

Parameters:

request (Union[HttpRequest, Request, ASGIRequest, None]) – The request object to check. This can be an instance of django.http.HttpRequest, rest_framework.request.Request, or django.core.handlers.wsgi.ASGIRequest. If None is provided, the function will return False.

Returns:

Returns True if the request is authenticated (i.e., the request has a user attribute and user.is_authenticated is True). Returns False otherwise.

Return type:

bool

Raises:

Exception – Any unexpected error during attribute access will be caught and logged; the function will return False in such cases.

Note

This function is compatible with Django and Django REST Framework request objects. It also supports ASGIRequest and can be used in unit tests with mock objects that have the required attributes.

Warning

If the request object does not have a user attribute, or if user.is_authenticated is not available, the function will return False. Any exceptions are logged as warnings.

Example usage:

from smarter.common.utils import is_authenticated_request
from django.http import HttpRequest

request = HttpRequest()
request.user = SomeUserObject()
authenticated = is_authenticated_request(request)
print(authenticated)  # True or False depending on user.is_authenticated
# Example with DRF Request
from rest_framework.request import Request

drf_request = Request(...)
authenticated = is_authenticated_request(drf_request)
print(authenticated)