Skip to content

Commit

Permalink
Fix unexpected Vary
Browse files Browse the repository at this point in the history
  • Loading branch information
jrobichaud committed Jan 11, 2025
1 parent f52be35 commit 194b918
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion django_structlog/middlewares/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from django.core.exceptions import PermissionDenied
from django.core.signals import got_request_exception
from django.http import Http404, StreamingHttpResponse
from django.utils.functional import SimpleLazyObject

from .. import signals
from ..app_settings import app_settings
Expand All @@ -39,6 +40,7 @@
if TYPE_CHECKING: # pragma: no cover
from types import TracebackType

from django.contrib.auth.base_user import AbstractBaseUser
from django.http import HttpRequest, HttpResponse

logger = structlog.getLogger(__name__)
Expand Down Expand Up @@ -207,13 +209,30 @@ def format_request(request: "HttpRequest") -> str:
@staticmethod
def bind_user_id(request: "HttpRequest") -> None:
user_id_field = app_settings.USER_ID_FIELD
if hasattr(request, "user") and request.user is not None and user_id_field:
if not user_id_field:
return

Check warning on line 213 in django_structlog/middlewares/request.py

View check run for this annotation

Codecov / codecov/patch

django_structlog/middlewares/request.py#L213

Added line #L213 was not covered by tests

session_was_accessed = (
request.session.accessed if hasattr(request, "session") else None
)

if hasattr(request, "user") and request.user is not None:
user_id = None
if hasattr(request.user, user_id_field):
user_id = getattr(request.user, user_id_field)
if isinstance(user_id, uuid.UUID):
user_id = str(user_id)
structlog.contextvars.bind_contextvars(user_id=user_id)
if session_was_accessed is not None and not session_was_accessed:
"""using SessionMiddleware but user was never accessed, must reset accessed state"""
user = request.user

def get_user() -> Any:
request.session.accessed = True
return user

request.user = cast("AbstractBaseUser", SimpleLazyObject(get_user))
request.session.accessed = False

def process_got_request_exception(
self, sender: Type[Any], request: "HttpRequest", **kwargs: Any
Expand Down

0 comments on commit 194b918

Please sign in to comment.