From e846c5e7246a0ffbe5dcf07a2b6c7c2a47537eb3 Mon Sep 17 00:00:00 2001 From: Jon Janzen Date: Mon, 13 Feb 2023 18:24:35 -0500 Subject: Fixed #31920 -- Made AuthenticationMiddleware add request.auser(). --- docs/ref/request-response.txt | 14 ++++++++++++++ docs/releases/5.0.txt | 3 +++ docs/topics/auth/default.txt | 15 +++++++++++++++ 3 files changed, 32 insertions(+) (limited to 'docs') diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index 9b0ed76e4d..9b71adfdf9 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -281,9 +281,23 @@ middleware class is listed in :setting:`MIDDLEWARE`. else: ... # Do something for anonymous users. + The :meth:`auser` method does the same thing but can be used from async + contexts. + Methods ------- +.. method:: HttpRequest.auser() + + .. versionadded:: 5.0 + + From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`: + Coroutine. Returns an instance of :setting:`AUTH_USER_MODEL` representing + the currently logged-in user. If the user isn't currently logged in, + ``auser`` will return an instance of + :class:`~django.contrib.auth.models.AnonymousUser`. This is similar to the + :attr:`user` attribute but it works in async contexts. + .. method:: HttpRequest.get_host() Returns the originating host of the request using information from the diff --git a/docs/releases/5.0.txt b/docs/releases/5.0.txt index 83cb6284a5..21ab783f86 100644 --- a/docs/releases/5.0.txt +++ b/docs/releases/5.0.txt @@ -65,6 +65,9 @@ Minor features * The default iteration count for the PBKDF2 password hasher is increased from 600,000 to 720,000. +* ``AuthenticationMiddleware`` now adds an :meth:`.HttpRequest.auser` + asynchronous method that returns the currently logged-in user. + :mod:`django.contrib.contenttypes` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt index a93201fb09..c705abcb6b 100644 --- a/docs/topics/auth/default.txt +++ b/docs/topics/auth/default.txt @@ -368,6 +368,7 @@ Django uses :doc:`sessions ` and middleware to hook the authentication system into :class:`request objects `. These provide a :attr:`request.user ` attribute +and a :meth:`request.auser ` async method on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an @@ -383,6 +384,20 @@ You can tell them apart with # Do something for anonymous users. ... +Or in an asynchronous view:: + + user = await request.auser() + if user.is_authenticated: + # Do something for authenticated users. + ... + else: + # Do something for anonymous users. + ... + +.. versionchanged:: 5.0 + + The :meth:`.HttpRequest.auser` method was added. + .. _how-to-log-a-user-in: How to log a user in -- cgit v1.2.1