Projet

Général

Profil

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

Benjamin Dauvergne, 06 mars 2015 16:25

Télécharger (2,73 ko)

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 |  8 ++++++++
 2 files changed, 34 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
425 425
        values_set.add(unicode(value))
426 426
    return values_set
427 427

  
428 428
def attribute_values_to_identifier(values):
429 429
    '''Try to find an identifier from attribute values'''
430 430
    normalized = normalize_attribute_values(values)
431 431
    assert len(normalized) == 1, 'multi-valued attribute cannot be used as an identifier'
432 432
    return list(normalized)[0]
433

  
434
def csrf_token_check(request, form):
435
    '''Check a request for CSRF cookie validation, and add an error to the form
436
       if check fails.
437
    '''
438
    if form.is_valid() and not getattr(request, 'csrf_processing_done', False):
439
        msg = _('The form was out of date, please try again.')
440
        form._errors[NON_FIELD_ERRORS] = ErrorList([msg])
433
-