Skip to content

Commit

Permalink
feat: make use of HttpRequest.auser() (from Django 5.x) during asyn…
Browse files Browse the repository at this point in the history
…c middleware (#22)
  • Loading branch information
axieum authored Dec 7, 2023
1 parent 3c8b4cb commit c9e45ee
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 14 deletions.
15 changes: 7 additions & 8 deletions src/django_user_trace/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import logging
from typing import TYPE_CHECKING

from asgiref.sync import sync_to_async
from django.core.exceptions import ImproperlyConfigured
from django.utils.decorators import sync_and_async_middleware

Expand All @@ -16,6 +15,7 @@
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable

from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
from django.http import HttpRequest, HttpResponse

GetResponseCallable = Callable[[HttpRequest], HttpResponse | Awaitable[HttpResponse]]
Expand All @@ -24,15 +24,16 @@
logger: logging.Logger = logging.getLogger(__name__)


def process_incoming_request(request: HttpRequest) -> None:
def process_incoming_request(request: HttpRequest, user: AbstractBaseUser | AnonymousUser | None = None) -> None:
"""
Processes an incoming HTTP request.
:param request: http request
:param user: Django user
"""

# Check that authentication has been performed by an earlier middleware
if not hasattr(request, "user"):
if not user:
raise ImproperlyConfigured(
"The django-user-trace middleware requires authentication middleware to be installed. "
"Edit your MIDDLEWARE setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' "
Expand All @@ -44,7 +45,7 @@ def process_incoming_request(request: HttpRequest) -> None:
{
key: (
val
if (val := lookup(request.user, request) if callable(lookup) else rgetattr(request.user, lookup, None))
if (val := lookup(user, request) if callable(lookup) else rgetattr(user, lookup, None))
not in (None, "")
else None
)
Expand Down Expand Up @@ -82,9 +83,7 @@ def django_user_trace_middleware(get_response: GetResponseCallable) -> GetRespon

async def middleware(request: HttpRequest) -> HttpResponse:
logger.debug("async middleware called")
if hasattr(request, "user"):
await sync_to_async(request.user._setup)() # type: ignore
process_incoming_request(request)
process_incoming_request(request, await request.auser() if hasattr(request, "auser") else None)
res: HttpResponse = await get_response(request)
process_outgoing_request(request)
return res
Expand All @@ -94,7 +93,7 @@ async def middleware(request: HttpRequest) -> HttpResponse:

def middleware(request: HttpRequest) -> HttpResponse: # type: ignore[misc]
logger.debug("sync middleware called")
process_incoming_request(request)
process_incoming_request(request, getattr(request, "user", None))
res: HttpResponse = get_response(request) # type: ignore
process_outgoing_request(request)
return res
Expand Down
6 changes: 0 additions & 6 deletions src/django_user_trace/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Any, Final

from django.db.models.constants import LOOKUP_SEP
from django.utils.functional import LazyObject, empty

SENTINEL: Final[object] = object()

Expand Down Expand Up @@ -43,11 +42,6 @@ def _resolve_attr(obj: Any, attr: str) -> Any:
:raise Exception: if unable to resolve the attribute
"""

if isinstance(obj, LazyObject): # unwrap lazy objects
if obj._wrapped is empty: # type: ignore[attr-defined]
obj._setup() # type: ignore[attr-defined]
obj = obj._wrapped # type: ignore[attr-defined]

result: Any
if obj is None:
raise AttributeError(f"{type(obj).__name__!r} object has no attribute {attr!r}")
Expand Down

0 comments on commit c9e45ee

Please sign in to comment.