middleware.py 1.35 KB
Newer Older
1 2 3 4 5 6 7 8
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.utils.functional import SimpleLazyObject
from usermerge import auth

# Create your middleware here.
# https://docs.djangoproject.com/en/2.0/topics/http/middleware/

9
# AuthenticationMiddleware is a middleware component that associates the current user with every incoming web request. Original source code for the get_user() function and the aforementioned component can be found in https://github.com/django/django/blob/master/django/contrib/auth/middleware.py (for more information, see https://docs.djangoproject.com/en/2.0/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware).
10

11 12 13 14 15 16 17 18
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user

class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        assert hasattr(request, 'session'), (
19 20 21
            'The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE%s setting to '
            'insert "django.contrib.sessions.middleware.SessionMiddleware" before "usermerge.middleware.AuthenticationMiddleware".'
        ) % ('_CLASSES' if settings.MIDDLEWARE is None else '')
22
        request.user = SimpleLazyObject(lambda: get_user(request))