|
1 from django.core.context_processors import PermWrapper |
|
2 from django.utils.functional import lazy, memoize, SimpleLazyObject |
|
3 from django.contrib import messages |
|
4 |
|
5 def auth(request): |
|
6 """ |
|
7 Returns context variables required by apps that use Django's authentication |
|
8 system. |
|
9 |
|
10 If there is no 'user' attribute in the request, uses AnonymousUser (from |
|
11 django.contrib.auth). |
|
12 """ |
|
13 # If we access request.user, request.session is accessed, which results in |
|
14 # 'Vary: Cookie' being sent in every request that uses this context |
|
15 # processor, which can easily be every request on a site if |
|
16 # TEMPLATE_CONTEXT_PROCESSORS has this context processor added. This kills |
|
17 # the ability to cache. So, we carefully ensure these attributes are lazy. |
|
18 # We don't use django.utils.functional.lazy() for User, because that |
|
19 # requires knowing the class of the object we want to proxy, which could |
|
20 # break with custom auth backends. LazyObject is a less complete but more |
|
21 # flexible solution that is a good enough wrapper for 'User'. |
|
22 def get_user(): |
|
23 if hasattr(request, 'user'): |
|
24 return request.user |
|
25 else: |
|
26 from django.contrib.auth.models import AnonymousUser |
|
27 return AnonymousUser() |
|
28 |
|
29 return { |
|
30 'user': SimpleLazyObject(get_user), |
|
31 'messages': messages.get_messages(request), |
|
32 'perms': lazy(lambda: PermWrapper(get_user()), PermWrapper)(), |
|
33 } |