0002-Allow-validation-of-CSRF-cookie-to-be-done-in-view-u.patch
src/authentic2/cbv.py | ||
---|---|---|
1 |
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt |
|
2 | ||
3 |
from django.utils.decorators import method_decorator |
|
4 |
from django.forms import Form |
|
5 | ||
6 |
from . import utils |
|
7 | ||
8 |
class ValidateCSRFMixin(object): |
|
9 |
'''Move CSRF token validation inside the form validation. |
|
10 | ||
11 |
This mixin must always be the leftest one and if your class override |
|
12 |
form_valid() or dispatch() you should move those overrides in a base |
|
13 |
class. |
|
14 |
''' |
|
15 |
@method_decorator(csrf_exempt) |
|
16 |
def dispatch(self, *args, **kwargs): |
|
17 |
return super(ValidateCSRFMixin, self).dispatch(*args, **kwargs) |
|
18 | ||
19 |
@method_decorator(ensure_csrf_cookie) |
|
20 |
def form_valid(self, *args, **kwargs): |
|
21 |
for form in args: |
|
22 |
if isinstance(form, Form): |
|
23 |
utils.csrf_token_check(self.request, form) |
|
24 |
if not form.is_valid(): |
|
25 |
return self.form_invalid(form) |
|
26 |
return super(ValidateCSRFMixin, self).form_valid(*args, **kwargs) |
src/authentic2/utils.py | ||
---|---|---|
17 | 17 |
from django import forms |
18 | 18 |
from django.forms.util import ErrorList |
19 | 19 |
from django.utils import html, http |
20 |
from django.utils.translation import ugettext as _ |
|
20 | 21 | |
21 | 22 |
from authentic2.saml.saml2utils import filter_attribute_private_key, \ |
22 | 23 |
filter_element_private_key |
... | ... | |
430 | 431 |
normalized = normalize_attribute_values(values) |
431 | 432 |
assert len(normalized) == 1, 'multi-valued attribute cannot be used as an identifier' |
432 | 433 |
return list(normalized)[0] |
434 | ||
435 |
def csrf_token_check(request, form): |
|
436 |
'''Check a request for CSRF cookie validation, and add an error to the form |
|
437 |
if check fails. |
|
438 |
''' |
|
439 |
if form.is_valid() and not getattr(request, 'csrf_processing_done', False): |
|
440 |
msg = _('The form was out of date, please try again.') |
|
441 |
form._errors[forms.forms.NON_FIELD_ERRORS] = ErrorList([msg]) |
|
433 |
- |