Esempio n. 1
0
def get_or_create_csrf_token(request):
    token = request.META.get('CSRF_COOKIE', None)
    if token is None:
        token = csrf._get_new_csrf_string()
        request.META['CSRF_COOKIE'] = token
    request.META['CSRF_COOKIE_USED'] = True
    return token
Esempio n. 2
0
    def test_csrf_validation_passes_after_process_request_login(self):
        """
        CSRF check must access the CSRF token from the session or cookie,
        rather than the request, as rotate_token() may have been called by an
        authentication middleware during the process_request() phase.
        """
        csrf_client = Client(enforce_csrf_checks=True)
        csrf_secret = _get_new_csrf_string()
        csrf_token = _mask_cipher_secret(csrf_secret)
        csrf_token_form = _mask_cipher_secret(csrf_secret)
        headers = {self.header: 'fakeuser'}
        data = {'csrfmiddlewaretoken': csrf_token_form}

        # Verify that CSRF is configured for the view
        csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
        response = csrf_client.post('/remote_user/', **headers)
        self.assertEqual(response.status_code, 403)
        self.assertIn(b'CSRF verification failed.', response.content)

        # This request will call django.contrib.auth.login() which will call
        # django.middleware.csrf.rotate_token() thus changing the value of
        # request.META['CSRF_COOKIE'] from the user submitted value set by
        # CsrfViewMiddleware.process_request() to the new csrftoken value set
        # by rotate_token(). Csrf validation should still pass when the view is
        # later processed by CsrfViewMiddleware.process_view()
        csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
        response = csrf_client.post('/remote_user/', data, **headers)
        self.assertEqual(response.status_code, 200)
Esempio n. 3
0
def test_disable_csrf():
    form = SampleForm()
    helper = FormHelper()
    helper.disable_csrf = True
    html = render_crispy_form(form, helper,
                              {"csrf_token": _get_new_csrf_string()})
    assert "csrf" not in html
def test_formset_layout(settings):
    SampleFormSet = formset_factory(SampleForm, extra=3)
    formset = SampleFormSet()
    helper = FormHelper()
    helper.form_id = 'thisFormsetRocks'
    helper.form_class = 'formsets-that-rock'
    helper.form_method = 'POST'
    helper.form_action = 'simpleAction'
    helper.layout = Layout(
        Fieldset(
            "Item {{ forloop.counter }}",
            'is_company',
            'email',
        ), HTML("{% if forloop.first %}Note for first form only{% endif %}"),
        Row('password1', 'password2'), Fieldset("", 'first_name', 'last_name'))

    html = render_crispy_form(form=formset,
                              helper=helper,
                              context={'csrf_token': _get_new_csrf_string()})

    # Check formset fields
    assert contains_partial(
        html,
        '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>'
    )
    assert contains_partial(
        html,
        '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>'
    )
    assert contains_partial(
        html,
        '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>'
    )
    assert contains_partial(
        html,
        '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>'
    )
    assert html.count("hidden") == 5

    # Check form structure
    assert html.count('<form') == 1
    assert html.count('csrfmiddlewaretoken') == 1
    assert 'formsets-that-rock' in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse('simpleAction') in html

    # Check form layout
    assert 'Item 1' in html
    assert 'Item 2' in html
    assert 'Item 3' in html
    assert html.count('Note for first form only') == 1
    if settings.CRISPY_TEMPLATE_PACK == 'uni_form':
        assert html.count('formRow') == 3
    elif settings.CRISPY_TEMPLATE_PACK in ('bootstrap3', 'bootstrap4'):
        assert html.count('row') == 3

    if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4':
        assert html.count('form-group') == 18
Esempio n. 5
0
def renew_csrf(window_info):
    if not window_info.csrf_cookie:
        csrf_secret = _get_new_csrf_string()
        window_info.csrf_cookie = _salt_cipher_secret(csrf_secret)
    else:
        csrf_secret = _unsalt_cipher_token(window_info.csrf_cookie)
    value = _salt_cipher_secret(csrf_secret)
    scall(window_info, "df.validate.update_csrf", to=[WINDOW], value=value)
Esempio n. 6
0
def renew_csrf(window_info):
    if not window_info.csrf_cookie:
        csrf_secret = _get_new_csrf_string()
        window_info.csrf_cookie = _salt_cipher_secret(csrf_secret)
    else:
        csrf_secret = _unsalt_cipher_token(window_info.csrf_cookie)
    value = _salt_cipher_secret(csrf_secret)
    scall(window_info, "df.validate.update_csrf", to=[WINDOW], value=value)
Esempio n. 7
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     token, created = Token.objects.get_or_create(user=user)
     auth_login(request, user)
     response = Response({'token': token.key})
     csrf_token = _get_new_csrf_string()
     response.set_cookie('csrftoken', csrf_token)
     return response
Esempio n. 8
0
def test_formset_layout(settings):
    SampleFormSet = formset_factory(SampleForm, extra=3)
    formset = SampleFormSet()
    helper = FormHelper()
    helper.form_id = "thisFormsetRocks"
    helper.form_class = "formsets-that-rock"
    helper.form_method = "POST"
    helper.form_action = "simpleAction"
    helper.layout = Layout(
        Fieldset(
            "Item {{ forloop.counter }}",
            "is_company",
            "email",
        ),
        HTML("{% if forloop.first %}Note for first form only{% endif %}"),
        Row("password1", "password2"),
        Fieldset("", "first_name", "last_name"),
    )

    html = render_crispy_form(form=formset, helper=helper, context={"csrf_token": _get_new_csrf_string()})

    # Check formset fields
    assert contains_partial(html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>')
    assert contains_partial(
        html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>'
    )
    assert contains_partial(
        html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>'
    )
    assert contains_partial(
        html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>'
    )
    assert html.count("hidden") == 5

    # Check form structure
    assert html.count("<form") == 1
    assert html.count("csrfmiddlewaretoken") == 1
    assert "formsets-that-rock" in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse("simpleAction") in html

    # Check form layout
    assert "Item 1" in html
    assert "Item 2" in html
    assert "Item 3" in html
    assert html.count("Note for first form only") == 1
    if settings.CRISPY_TEMPLATE_PACK == "uni_form":
        assert html.count("formRow") == 3
    elif settings.CRISPY_TEMPLATE_PACK in ("bootstrap3", "bootstrap4"):
        assert html.count("row") == 3

    if settings.CRISPY_TEMPLATE_PACK == "bootstrap4":
        assert html.count("form-group") == 18
Esempio n. 9
0
def test_CSRF_token_GET_form():
    form_helper = FormHelper()
    form_helper.form_method = "GET"
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """)

    c = Context({
        "form": SampleForm(),
        "form_helper": form_helper,
        "csrf_token": _get_new_csrf_string()
    })
    html = template.render(c)

    assert "csrfmiddlewaretoken" not in html
Esempio n. 10
0
def test_CSRF_token_GET_form():
    form_helper = FormHelper()
    form_helper.form_method = 'GET'
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """)

    c = Context({
        'form': SampleForm(),
        'form_helper': form_helper,
        'csrf_token': _get_new_csrf_string()
    })
    html = template.render(c)

    assert 'csrfmiddlewaretoken' not in html
Esempio n. 11
0
def test_CSRF_token_POST_form():
    form_helper = FormHelper()
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """)

    # The middleware only initializes the CSRF token when processing a real request
    # So using RequestContext or csrf(request) here does not work.
    # Instead I set the key `csrf_token` to a CSRF token manually, which `csrf_token` tag uses
    c = Context({
        "form": SampleForm(),
        "form_helper": form_helper,
        "csrf_token": _get_new_csrf_string()
    })
    html = template.render(c)

    assert "csrfmiddlewaretoken" in html
Esempio n. 12
0
    def _build_mock_request(self, user=None, get=None, post=None):
        request = MagicMock()
        if user:
            request.user = user
            if django.VERSION[0] == 1:
                request.user.is_authenticated.__get__ = MagicMock(
                    return_value=True)
            elif django.VERSION[0] >= 2:
                request.user.__dict__['is_authenticated'] = True
        else:
            request.user = AnonymousUser()

        csrf = _salt_cipher_secret(_get_new_csrf_string())
        request.GET = {}
        request.POST = {}
        request.META = {"SCRIPT_NAME": "/"}
        request.COOKIES = {settings.CSRF_COOKIE_NAME: csrf}
        request.resolver_match.kwargs = {}
        if get is not None:
            request.GET.update(get)
        if post is not None:
            request.POST.update(post)
        return request
Esempio n. 13
0
def test_formset_with_helper_without_layout(settings):
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy testFormSet formset_helper %}
    """)

    form_helper = FormHelper()
    form_helper.form_id = "thisFormsetRocks"
    form_helper.form_class = "formsets-that-rock"
    form_helper.form_method = "POST"
    form_helper.form_action = "simpleAction"

    SampleFormSet = formset_factory(SampleForm, extra=3)
    testFormSet = SampleFormSet()

    c = Context({
        "testFormSet": testFormSet,
        "formset_helper": form_helper,
        "csrf_token": _get_new_csrf_string()
    })
    html = template.render(c)

    assert html.count("<form") == 1
    assert html.count("csrfmiddlewaretoken") == 1

    # Check formset management form
    assert "form-TOTAL_FORMS" in html
    assert "form-INITIAL_FORMS" in html
    assert "form-MAX_NUM_FORMS" in html

    assert "formsets-that-rock" in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse("simpleAction") in html
    if settings.CRISPY_TEMPLATE_PACK == "uni_form":
        assert 'class="uniForm' in html
Esempio n. 14
0
def test_formset_with_helper_without_layout(settings):
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy testFormSet formset_helper %}
    """)

    form_helper = FormHelper()
    form_helper.form_id = 'thisFormsetRocks'
    form_helper.form_class = 'formsets-that-rock'
    form_helper.form_method = 'POST'
    form_helper.form_action = 'simpleAction'

    SampleFormSet = formset_factory(SampleForm, extra=3)
    testFormSet = SampleFormSet()

    c = Context({
        'testFormSet': testFormSet,
        'formset_helper': form_helper,
        'csrf_token': _get_new_csrf_string()
    })
    html = template.render(c)

    assert html.count('<form') == 1
    assert html.count('csrfmiddlewaretoken') == 1

    # Check formset management form
    assert 'form-TOTAL_FORMS' in html
    assert 'form-INITIAL_FORMS' in html
    assert 'form-MAX_NUM_FORMS' in html

    assert 'formsets-that-rock' in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse('simpleAction') in html
    if settings.CRISPY_TEMPLATE_PACK == 'uni_form':
        assert 'class="uniForm' in html
Esempio n. 15
0
 def get(self, request, *args, **kwargs):
     response = render(request, 'index.html')
     response.set_cookie('csrftoken', _get_new_csrf_string())
     return response
 def _get_new_csrf_token():
     return _mask_cipher_secret(_get_new_csrf_string())