Projet

Général

Profil

0002-Allow-validation-of-CSRF-cookie-to-be-done-in-view-u.patch

Voir les différences:

Subject: [PATCH 2/5] Allow validation of CSRF cookie to be done in view using
 a CBV mixin or an helper function (refs #5617)

Use the CBV for a do-nothing use or on a function based view you must
apply the decorators @csrf_exempt and @ensure_csrf_cookie on your view
(in this order) and use utils.csrf_token_check(request, form) to check
for the cookie before validating your form.
 src/authentic2/cbv.py   | 26 ++++++++++++++++++++++++++
 src/authentic2/utils.py |  9 +++++++++
 2 files changed, 35 insertions(+)
 create mode 100644 src/authentic2/cbv.py
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
-