authentication.py 741 B

1234567891011121314151617181920212223
  1. from asgiref.sync import sync_to_async
  2. from django.conf import settings
  3. from django.contrib.auth import SESSION_KEY
  4. from django.http import HttpRequest
  5. class AuthHttpRequest(HttpRequest):
  6. """Django HttpRequest that is known to be authenticated by a user"""
  7. auth: str
  8. "User ID"
  9. async def django_auth(request: HttpRequest):
  10. """
  11. Check if user is logged in by checking session
  12. This avoids an unnecessary database call.
  13. request.auth will result in the user id
  14. """
  15. if settings.SESSION_ENGINE == "django.contrib.sessions.backends.cache":
  16. return request.session.get(SESSION_KEY)
  17. # Django DB backed sessions don't support async yet
  18. return await sync_to_async(request.session.get)(SESSION_KEY)