|
1 from django.middleware.csrf import CsrfViewMiddleware |
|
2 from django.utils.decorators import decorator_from_middleware, available_attrs |
|
3 |
|
4 try: |
|
5 from functools import wraps |
|
6 except ImportError: |
|
7 from django.utils.functional import wraps # Python 2.4 fallback. |
|
8 |
|
9 csrf_protect = decorator_from_middleware(CsrfViewMiddleware) |
|
10 csrf_protect.__name__ = "csrf_protect" |
|
11 csrf_protect.__doc__ = """ |
|
12 This decorator adds CSRF protection in exactly the same way as |
|
13 CsrfViewMiddleware, but it can be used on a per view basis. Using both, or |
|
14 using the decorator multiple times, is harmless and efficient. |
|
15 """ |
|
16 |
|
17 def csrf_response_exempt(view_func): |
|
18 """ |
|
19 Modifies a view function so that its response is exempt |
|
20 from the post-processing of the CSRF middleware. |
|
21 """ |
|
22 def wrapped_view(*args, **kwargs): |
|
23 resp = view_func(*args, **kwargs) |
|
24 resp.csrf_exempt = True |
|
25 return resp |
|
26 return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) |
|
27 |
|
28 def csrf_view_exempt(view_func): |
|
29 """ |
|
30 Marks a view function as being exempt from CSRF view protection. |
|
31 """ |
|
32 # We could just do view_func.csrf_exempt = True, but decorators |
|
33 # are nicer if they don't have side-effects, so we return a new |
|
34 # function. |
|
35 def wrapped_view(*args, **kwargs): |
|
36 return view_func(*args, **kwargs) |
|
37 wrapped_view.csrf_exempt = True |
|
38 return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) |
|
39 |
|
40 def csrf_exempt(view_func): |
|
41 """ |
|
42 Marks a view function as being exempt from the CSRF checks |
|
43 and post processing. |
|
44 |
|
45 This is the same as using both the csrf_view_exempt and |
|
46 csrf_response_exempt decorators. |
|
47 """ |
|
48 return csrf_response_exempt(csrf_view_exempt(view_func)) |