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 ofdjango.http.HttpRequest,rest_framework.request.Request, ordjango.core.handlers.wsgi.ASGIRequest. IfNoneis provided, the function will returnFalse.- Returns:
Returns
Trueif the request is authenticated (i.e., the request has auserattribute anduser.is_authenticatedisTrue). ReturnsFalseotherwise.- Return type:
- Raises:
Exception – Any unexpected error during attribute access will be caught and logged; the function will return
Falsein 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
userattribute, or ifuser.is_authenticatedis not available, the function will returnFalse. 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)