def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Exemple #2
0
def my_ajax_view(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = ProjectForm()


    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = ProjectForm(form_data)
        if form.is_valid():
            form.save()

    field_configuration = {
        'include': ['title','duration'],
    }

    remote_form = RemoteForm(form, **field_configuration)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        mimetype="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
Exemple #3
0
 def post(self, request, *args, **kwargs):
     
     # Check CSRF manually *after* initializing the file upload handlers.
     csrf_checker = CsrfViewMiddleware()
     csrf_error = csrf_checker.process_view(request, None, None, None)
     if csrf_error is not None:
         return csrf_error # csrf_error is the regular CSRF error View
     
     
     form = self.form_class(request.POST, request.FILES)
     if form.is_valid():
         #form.save()
         self.filename=request.FILES['csv_file'].temporary_file_path()  
         
         logger.info("Starting catalogue import")
         importer = TernovoPriceImporter(logger, delimiter=";")
     
         logger.info(" - Importing records from '%s'" % self.filename)
         try:
            stats=importer.handle(self.filename)
         except CatalogueImportError as e:
             raise CommandError(str(e))
         
                     
         #return redirect(reverse_lazy('dashboard:import-success', kwargs = {'filename': self.filename}))
         return render(request,self.template_name, {'form': form, 'filename': request.FILES['csv_file'].name, 'stats': stats})
     else:
         return render(request, self.template_name, {'form': form})
Exemple #4
0
    def test_process_response_get_token_used(self):
        """
        When get_token is used, check that the cookie is created and headers
        patched.
        """
        req = self._get_GET_no_csrf_cookie_request()

        # Put tests for CSRF_COOKIE_* settings here
        with self.settings(
            CSRF_COOKIE_NAME="myname",
            CSRF_COOKIE_DOMAIN=".example.com",
            CSRF_COOKIE_PATH="/test/",
            CSRF_COOKIE_SECURE=True,
            CSRF_COOKIE_HTTPONLY=True,
        ):
            # token_view calls get_token() indirectly
            CsrfViewMiddleware().process_view(req, token_view, (), {})
            resp = token_view(req)
            resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get("myname", False)
        self.assertIsNot(csrf_cookie, False)
        self.assertEqual(csrf_cookie["domain"], ".example.com")
        self.assertIs(csrf_cookie["secure"], True)
        self.assertIs(csrf_cookie["httponly"], True)
        self.assertEqual(csrf_cookie["path"], "/test/")
        self.assertIn("Cookie", resp2.get("Vary", ""))
Exemple #5
0
 def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
     """
     Extracts the common "which-format/serialize/return-response" cycle.
     Also, since we're dealing with forms, process the response for
     CSRF protection.
     """
     csrf_middleware = CsrfViewMiddleware()
     response = super(BaseFormResource, self).create_response(request, data, response_class, **response_kwargs)
     return csrf_middleware.process_response(request, response)
Exemple #6
0
 def test_ensures_csrf_cookie_with_middleware(self):
     """
     The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
     enabled.
     """
     req = self._get_GET_no_csrf_cookie_request()
     CsrfViewMiddleware().process_view(req, ensure_csrf_cookie_view, (), {})
     resp = ensure_csrf_cookie_view(req)
     resp2 = CsrfViewMiddleware().process_response(req, resp)
     self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
     self.assertIn('Cookie', resp2.get('Vary', ''))
Exemple #7
0
    def test_process_response_get_token_used(self):
        """
        When get_token is used, check that the cookie is created and headers
        patched.
        """
        req = self._get_GET_no_csrf_cookie_request()
        # token_view calls get_token() indirectly
        CsrfViewMiddleware().process_view(req, token_view, (), {})
        resp = token_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)

        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
        self.assertNotEqual(csrf_cookie, False)
        self.assertTrue('Cookie' in resp2.get('Vary',''))
Exemple #8
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
         not request.user.is_authenticated()):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         if response is None:
             request._update_cache = True
         else:
             csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
             if csrf_mw_name in settings.MIDDLEWARE_CLASSES:
                 csrf_mw = CsrfViewMiddleware()
                 csrf_mw.process_view(request, lambda x: None, None, None)
                 get_token(request)
             return HttpResponse(response)
Exemple #9
0
    def test_ensures_csrf_cookie_with_middleware(self):
        """
        The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
        enabled.
        """
        @ensure_csrf_cookie
        def view(request):
            # Doesn't insert a token or anything
            return HttpResponse(content="")

        req = self._get_GET_no_csrf_cookie_request()
        CsrfViewMiddleware().process_view(req, view, (), {})
        resp = view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
        self.assertIn('Cookie', resp2.get('Vary', ''))
Exemple #10
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
             not is_authenticated(request.user)):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receieve one on their first request, with cache
         # middleware running.
         if csrf_middleware_installed():
             csrf_mw = CsrfViewMiddleware()
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
Exemple #11
0
    def test_ensures_csrf_cookie_with_middleware(self):
        """
        Tests that ensures_csrf_cookie decorator fulfils its promise
        with the middleware enabled.
        """

        @ensure_csrf_cookie
        def view(request):
            # Doesn't insert a token or anything
            return HttpResponse(content="")

        req = self._get_GET_no_csrf_cookie_request()
        CsrfViewMiddleware().process_view(req, view, (), {})
        resp = view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
        self.assertTrue("Cookie" in resp2.get("Vary", ""))
Exemple #12
0
    def test_process_response_get_token_not_used(self):
        """
        Check that if get_token() is not called, the view middleware does not
        add a cookie.
        """
        # This is important to make pages cacheable.  Pages which do call
        # get_token(), assuming they use the token, are not cacheable because
        # the token is specific to the user
        req = self._get_GET_no_csrf_cookie_request()
        # non_token_view_using_request_processor does not call get_token(), but
        # does use the csrf request processor.  By using this, we are testing
        # that the view processor is properly lazy and doesn't call get_token()
        # until needed.
        CsrfViewMiddleware().process_view(req, non_token_view_using_request_processor, (), {})
        resp = non_token_view_using_request_processor(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)

        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
        self.assertEqual(csrf_cookie, False)
Exemple #13
0
    def test_token_node_empty_csrf_cookie(self):
        """
        Check that we get a new token if the csrf_cookie is the empty string
        """
        req = self._get_GET_no_csrf_cookie_request()
        req.COOKIES[settings.CSRF_COOKIE_NAME] = b""
        CsrfViewMiddleware().process_view(req, token_view, (), {})
        resp = token_view(req)

        self.assertNotEqual("", resp.content)
Exemple #14
0
 def _test_https_good_referer_matches_cookie_domain_with_different_port(
         self):
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_REFERER'] = 'https://foo.example.com:4443/'
     req.META['SERVER_PORT'] = '4443'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertIsNone(response)
Exemple #15
0
 def process_request(self, request):
     if (
         cache_installed()
         and request.method == "GET"
         and not is_authenticated(request.user)
     ):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receive one on their first request, with cache
         # middleware running.
         if csrf_middleware_installed():
             csrf_mw = CsrfViewMiddleware(self.get_response)
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
Exemple #16
0
 def test_https_good_referer(self):
     """
     Test that a POST HTTPS request with a good referer is accepted
     """
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_REFERER'] = 'https://www.example.com/somepage'
     req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertEqual(None, req2)
Exemple #17
0
    def test_csrf_cookie_age(self):
        """
        CSRF cookie age can be set using settings.CSRF_COOKIE_AGE.
        """
        req = self._get_GET_no_csrf_cookie_request()

        MAX_AGE = 123
        with self.settings(CSRF_COOKIE_NAME='csrfcookie',
                           CSRF_COOKIE_DOMAIN='.example.com',
                           CSRF_COOKIE_AGE=MAX_AGE,
                           CSRF_COOKIE_PATH='/test/',
                           CSRF_COOKIE_SECURE=True,
                           CSRF_COOKIE_HTTPONLY=True):
            # token_view calls get_token() indirectly
            mw = CsrfViewMiddleware(token_view)
            mw.process_view(req, token_view, (), {})
            resp = mw(req)
            max_age = resp.cookies.get('csrfcookie').get('max-age')
            self.assertEqual(max_age, MAX_AGE)
Exemple #18
0
 def test_process_request_csrf_cookie_no_token_exempt_view(self):
     """
     Check that if a CSRF cookie is present and no token, but the csrf_exempt
     decorator has been applied to the view, the middleware lets it through
     """
     req = self._get_POST_csrf_cookie_request()
     req2 = CsrfViewMiddleware().process_view(req,
                                              csrf_exempt(post_form_view),
                                              (), {})
     self.assertIsNone(req2)
Exemple #19
0
    def test_post_data_read_failure(self):
        """
        OSErrors during POST data reading are caught and treated as if the
        POST data wasn't there (#20128).
        """
        class CsrfPostRequest(HttpRequest):
            """
            HttpRequest that can raise an OSError when accessing POST data
            """
            def __init__(self, token, raise_error):
                super().__init__()
                self.method = 'POST'

                self.raise_error = False
                self.COOKIES[settings.CSRF_COOKIE_NAME] = token

                # Handle both cases here to prevent duplicate code in the
                # session tests.
                self.session = {}
                self.session[CSRF_SESSION_KEY] = token

                self.POST['csrfmiddlewaretoken'] = token
                self.raise_error = raise_error

            def _load_post_and_files(self):
                raise OSError('error reading input data')

            def _get_post(self):
                if self.raise_error:
                    self._load_post_and_files()
                return self._post

            def _set_post(self, post):
                self._post = post

            POST = property(_get_post, _set_post)

        token = ('ABC' + self._csrf_id)[:CSRF_TOKEN_LENGTH]

        req = CsrfPostRequest(token, raise_error=False)
        mw = CsrfViewMiddleware(post_form_view)
        mw.process_request(req)
        resp = mw.process_view(req, post_form_view, (), {})
        self.assertIsNone(resp)

        req = CsrfPostRequest(token, raise_error=True)
        mw.process_request(req)
        with self.assertLogs('django.security.csrf', 'WARNING') as cm:
            resp = mw.process_view(req, post_form_view, (), {})
        self.assertEqual(resp.status_code, 403)
        self.assertEqual(cm.records[0].getMessage(),
                         'Forbidden (%s): ' % REASON_BAD_TOKEN)
Exemple #20
0
 def test_https_good_referer_matches_cookie_domain(self):
     """
     A POST HTTPS request with a good referer should be accepted from a
     subdomain that's allowed by CSRF_COOKIE_DOMAIN.
     """
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_REFERER'] = 'https://foo.example.com/'
     req.META['SERVER_PORT'] = '443'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertIsNone(response)
Exemple #21
0
    def test_csrf_token(self):
        request = HttpRequest()
        CsrfViewMiddleware(lambda req: HttpResponse()).process_view(request, lambda r: None, (), {})

        template = self.engine.get_template('template_backends/csrf.html')
        content = template.render(request=request)

        expected = '<input type="hidden" name="csrfmiddlewaretoken" value="([^"]+)">'
        match = re.match(expected, content) or re.match(expected.replace('"', "'"), content)
        self.assertTrue(match, "hidden csrftoken field not found in output")
        self.check_tokens_equivalent(match[1], get_token(request))
Exemple #22
0
    def test_csrf_token(self):
        request = HttpRequest()
        CsrfViewMiddleware().process_view(request, lambda r: None, (), {})

        template = self.engine.get_template('template_backends/csrf.html')
        content = template.render(request=request)

        expected = ('<input type="hidden" name="csrfmiddlewaretoken" '
                    'value="{}" />'.format(get_token(request)))

        self.assertHTMLEqual(content, expected)
Exemple #23
0
 def test_https_csrf_trusted_origin_allowed(self):
     """
     A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS
     setting is accepted.
     """
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_REFERER'] = 'https://dashboard.example.com'
     req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertIsNone(req2)
Exemple #24
0
    def test_csrf_cookie_age_none(self):
        """
        CSRF cookie age does not have max age set and therefore uses
        session-based cookies.
        """
        req = self._get_GET_no_csrf_cookie_request()

        MAX_AGE = None
        with self.settings(CSRF_COOKIE_NAME='csrfcookie',
                           CSRF_COOKIE_DOMAIN='.example.com',
                           CSRF_COOKIE_AGE=MAX_AGE,
                           CSRF_COOKIE_PATH='/test/',
                           CSRF_COOKIE_SECURE=True,
                           CSRF_COOKIE_HTTPONLY=True):
            # token_view calls get_token() indirectly
            mw = CsrfViewMiddleware(token_view)
            mw.process_view(req, token_view, (), {})
            resp = mw(req)
            max_age = resp.cookies.get('csrfcookie').get('max-age')
            self.assertEqual(max_age, '')
Exemple #25
0
 def test_https_malformed_referer(self):
     """
     Test that a POST HTTPS request with a bad referer is rejected
     """
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_REFERER'] = 'http://http://www.example.com/'
     req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertNotEqual(None, req2)
     self.assertEqual(403, req2.status_code)
Exemple #26
0
    def test_put_and_delete_rejected(self):
        """
        HTTP PUT and DELETE methods have protection
        """
        req = TestingHttpRequest()
        req.method = 'PUT'
        mw = CsrfViewMiddleware(post_form_view)
        with self.assertLogs('django.security.csrf', 'WARNING') as cm:
            resp = mw.process_view(req, post_form_view, (), {})
        self.assertEqual(403, resp.status_code)
        self.assertEqual(cm.records[0].getMessage(),
                         'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)

        req = TestingHttpRequest()
        req.method = 'DELETE'
        with self.assertLogs('django.security.csrf', 'WARNING') as cm:
            resp = mw.process_view(req, post_form_view, (), {})
        self.assertEqual(403, resp.status_code)
        self.assertEqual(cm.records[0].getMessage(),
                         'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
Exemple #27
0
    def test_token_node_empty_csrf_cookie(self):
        """
        Check that we get a new token if the csrf_cookie is the empty string
        """
        req = self._get_GET_no_csrf_cookie_request()
        req.COOKIES[settings.CSRF_COOKIE_NAME] = b""
        CsrfViewMiddleware().process_view(req, token_view, (), {})
        resp = token_view(req)

        token = get_token(req)
        self.assertIsNotNone(token)
        self._check_token_present(resp, token)
Exemple #28
0
 def test_https_good_referer_2(self):
     """
     A POST HTTPS request with a good referer is accepted where the referer
     contains no trailing slash.
     """
     # See ticket #15617
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_REFERER'] = 'https://www.example.com'
     req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertIsNone(req2)
Exemple #29
0
 def _test_https_good_referer_behind_proxy(self):
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META.update({
         'HTTP_HOST': '10.0.0.2',
         'HTTP_REFERER': 'https://www.example.com/somepage',
         'SERVER_PORT': '8080',
         'HTTP_X_FORWARDED_HOST': 'www.example.com',
         'HTTP_X_FORWARDED_PORT': '443',
     })
     req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
     self.assertIsNone(req2)
Exemple #30
0
 def test_bad_origin_csrf_trusted_origin_bad_protocol(self):
     """
     A request with an origin with the wrong protocol compared to
     CSRF_TRUSTED_ORIGINS is rejected.
     """
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_HOST'] = 'www.example.com'
     req.META['HTTP_ORIGIN'] = 'http://foo.example.com'
     mw = CsrfViewMiddleware(post_form_view)
     self.assertIs(mw._origin_verified(req), False)
     with self.assertLogs('django.security.csrf', 'WARNING') as cm:
         response = mw.process_view(req, post_form_view, (), {})
     self.assertEqual(response.status_code, 403)
     msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
     self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
     self.assertEqual(mw.allowed_origins_exact, {'http://no-match.com'})
     self.assertEqual(mw.allowed_origin_subdomains, {
         'https': ['.example.com'],
         'http': ['.no-match.com', '.no-match-2.com'],
     })
Exemple #31
0
    def test_put_and_delete_rejected(self):
        """
        HTTP PUT and DELETE methods have protection
        """
        req = TestingHttpRequest()
        req.method = 'PUT'
        with patch_logger('django.security.csrf', 'warning') as logger_calls:
            req2 = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                     {})
            self.assertEqual(403, req2.status_code)
            self.assertEqual(logger_calls[0],
                             'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)

        req = TestingHttpRequest()
        req.method = 'DELETE'
        with patch_logger('django.security.csrf', 'warning') as logger_calls:
            req2 = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                     {})
            self.assertEqual(403, req2.status_code)
            self.assertEqual(logger_calls[0],
                             'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
Exemple #32
0
 def test_process_request_csrf_cookie_no_token(self):
     """
     If a CSRF cookie is present but no token, the middleware rejects
     the incoming request.
     """
     with patch_logger('django.security.csrf', 'warning') as logger_calls:
         req = self._get_POST_csrf_cookie_request()
         req2 = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
         self.assertEqual(403, req2.status_code)
         self.assertEqual(logger_calls[0],
                          'Forbidden (%s): ' % REASON_BAD_TOKEN)
Exemple #33
0
 def test_process_request_no_csrf_cookie(self):
     """
     If no CSRF cookies is present, the middleware rejects the incoming
     request. This will stop login CSRF.
     """
     with patch_logger('django.security.csrf', 'warning') as logger_calls:
         req = self._get_POST_no_csrf_cookie_request()
         req2 = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
         self.assertEqual(403, req2.status_code)
         self.assertEqual(logger_calls[0],
                          'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
Exemple #34
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
def api_user_login_via_otp_form_email_django_forms_example(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = UserLoginViaOtpFormEmail(initial={'email': settings.TESTING_EMAIL2})
    elif request.method == 'POST':
        if request.content_type  != 'application/json':
            return HttpResponse(json.dumps({"detail": "Unsupported media type \"'%s'\" in request." % request.content_type}), content_type="application/json",status=401);
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = json.loads(request.body)
        form = UserLoginViaOtpFormEmail(form_data)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            response = HttpResponse(
                {'email': email},
                content_type="application/json"
            )

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        content_type="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
Exemple #36
0
def my_ajax_view(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = IngredientForm10()
    elif request.method == 'POST':
        #request.POST = json.loads(request.body)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = json.loads(request.body)
        form = IngredientForm10(form_data)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("ingredients-api:singleform"))

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder),
                            content_type="application/json")

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
Exemple #37
0
    def test_post_data_read_failure(self):
        """
        #20128 -- IOErrors during POST data reading should be caught and
        treated as if the POST data wasn't there.
        """
        class CsrfPostRequest(HttpRequest):
            """
            HttpRequest that can raise an IOError when accessing POST data
            """
            def __init__(self, token, raise_error):
                super(CsrfPostRequest, self).__init__()
                self.method = 'POST'

                self.raise_error = False
                self.COOKIES[settings.CSRF_COOKIE_NAME] = token
                self.POST['csrfmiddlewaretoken'] = token
                self.raise_error = raise_error

            def _load_post_and_files(self):
                raise IOError('error reading input data')

            def _get_post(self):
                if self.raise_error:
                    self._load_post_and_files()
                return self._post

            def _set_post(self, post):
                self._post = post

            POST = property(_get_post, _set_post)

        token = ('ABC' + self._csrf_id)[:CSRF_TOKEN_LENGTH]

        req = CsrfPostRequest(token, raise_error=False)
        resp = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
        self.assertIsNone(resp)

        req = CsrfPostRequest(token, raise_error=True)
        resp = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
        self.assertEqual(resp.status_code, 403)
Exemple #38
0
    def test_login_csrf_rotate(self, login=default_login, password='******'):
        """
        Makes sure that a login rotates the currently-used CSRF token.

        This is copy-pasted from django to allow specifying the login (username).
        """
        # Do a GET to establish a CSRF token
        # TestClient isn't used here as we're testing middleware, essentially.
        req = HttpRequest()
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        # get_token() triggers CSRF token inclusion in the response
        get_token(req)
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token1 = csrf_cookie.coded_value

        # Prepare the POST request
        req = HttpRequest()
        req.COOKIES[settings.CSRF_COOKIE_NAME] = token1
        req.method = "POST"
        req.POST = {
            'username': login,
            'password': password,
            'csrfmiddlewaretoken': token1
        }

        # Use POST request to log in
        SessionMiddleware().process_request(req)
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        req.META[
            "SERVER_NAME"] = "testserver"  # Required to have redirect work in login view
        req.META["SERVER_PORT"] = 80
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token2 = csrf_cookie.coded_value

        # Check the CSRF token switched
        self.assertNotEqual(token1, token2)
Exemple #39
0
    def test_login_csrf_rotate(self, password='******'):
        """
        Makes sure that a login rotates the currently-used CSRF token.
        """
        # Do a GET to establish a CSRF token
        # TestClient isn't used here as we're testing middleware, essentially.
        req = HttpRequest()
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        req.META["CSRF_COOKIE_USED"] = True
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token1 = csrf_cookie.coded_value

        # Prepare the POST request
        req = HttpRequest()
        req.COOKIES[settings.CSRF_COOKIE_NAME] = token1
        req.method = "POST"
        req.POST = {
            'username': '******',
            'password': password,
            'csrfmiddlewaretoken': token1
        }
        req.REQUEST = req.POST

        # Use POST request to log in
        SessionMiddleware().process_request(req)
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        req.META[
            "SERVER_NAME"] = "testserver"  # Required to have redirect work in login view
        req.META["SERVER_PORT"] = 80
        req.META["CSRF_COOKIE_USED"] = True
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token2 = csrf_cookie.coded_value

        # Check the CSRF token switched
        self.assertNotEqual(token1, token2)
Exemple #40
0
    def test_process_response_get_token_used(self):
        """
        When get_token is used, check that the cookie is created and headers
        patched.
        """
        req = self._get_GET_no_csrf_cookie_request()

        # Put tests for CSRF_COOKIE_* settings here
        with self.settings(CSRF_COOKIE_NAME='myname',
                           CSRF_COOKIE_DOMAIN='.example.com',
                           CSRF_COOKIE_PATH='/test/',
                           CSRF_COOKIE_SECURE=True):
            # token_view calls get_token() indirectly
            CsrfViewMiddleware().process_view(req, token_view, (), {})
            resp = token_view(req)
            resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get('myname', False)
        self.assertNotEqual(csrf_cookie, False)
        self.assertEqual(csrf_cookie['domain'], '.example.com')
        self.assertEqual(csrf_cookie['secure'], True)
        self.assertEqual(csrf_cookie['path'], '/test/')
        self.assertTrue('Cookie' in resp2.get('Vary',''))
Exemple #41
0
    def post(self, request, *args, **kwargs):
        reason = CsrfViewMiddleware().process_view(request, None, (), {})
        if reason:
            raise PermissionDenied

        person = get_or_create_person(request)

        form = ResendEmailVerificationForm(request.POST)
        if form.is_valid():
            email_object, created = get_email_object(person)
            email_object.send_confirmation()

        return super(GroupStatsView, self).get(request, *args, **kwargs)
Exemple #42
0
 def test_https_malformed_referer(self):
     """
     A POST HTTPS request with a bad referer is rejected.
     """
     malformed_referer_msg = 'Referer checking failed - Referer is malformed.'
     req = self._get_POST_request_with_token()
     req._is_secure_override = True
     req.META['HTTP_REFERER'] = 'http://http://www.example.com/'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertContains(
         response,
         'Referer checking failed - Referer is insecure while host is secure.',
         status_code=403,
     )
     # Empty
     req.META['HTTP_REFERER'] = ''
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertContains(response, malformed_referer_msg, status_code=403)
     # Non-ASCII
     req.META['HTTP_REFERER'] = b'\xd8B\xf6I\xdf'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertContains(response, malformed_referer_msg, status_code=403)
     # missing scheme
     # >>> urlparse('//example.com/')
     # ParseResult(scheme='', netloc='example.com', path='/', params='', query='', fragment='')
     req.META['HTTP_REFERER'] = '//example.com/'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertContains(response, malformed_referer_msg, status_code=403)
     # missing netloc
     # >>> urlparse('https://')
     # ParseResult(scheme='https', netloc='', path='', params='', query='', fragment='')
     req.META['HTTP_REFERER'] = 'https://'
     response = CsrfViewMiddleware().process_view(req, post_form_view, (),
                                                  {})
     self.assertContains(response, malformed_referer_msg, status_code=403)
Exemple #43
0
def json_topic_form(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        form = TopicForm()
    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)

        csrf_middleware.process_view(request, None, None, None, None)
        form_data = request.POST.get('data', {})
        form = TopicForm(form_data)
        if form.is_valid():
            form.save()

    remote_form = RemoteForm(form)

    response_data.update(remote_form_as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), mimetype='application/json')

    csrf_middleware.process_response(request, response)
    return response;
Exemple #44
0
 def check_csrf(self, request):
     csrf_middleware = CsrfViewMiddleware()
     response = csrf_middleware.process_view(request, self.deserialize, self.view.args, self.view.kwargs)
     if response is not None:
         assert False, 'csrf failed' #TODO APIException(response) or SuspiciousOperation ....
         raise response
Exemple #45
0
    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not request.user.is_authenticated()
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, '_messages'):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
        if csrf_mw_name in MIDDLEWARE_SETTING:
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response
Exemple #46
0
 def test_csrf(self, request):
     middleware = CsrfViewMiddleware()
     return middleware.process_view(request, self.dispatch, [request], {})
Exemple #47
0
def newmessage(request):
    from django.middleware.csrf import CsrfViewMiddleware
    csrf_middleware = CsrfViewMiddleware()
    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = BroadcastForm()
    elif request.method == 'POST':
        request.POST = json.loads(request.body)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = BroadcastForm(form_data)
        if form.is_valid():
            message = form.cleaned_data["message"]

            #Send Member
            if form.cleaned_data["member"]:
                queryset = _get_queryset(form)
                if queryset:
                    persons = Person.objects.filter(queryset)
                else:
                    persons = Person.objects.all()

                _send_sms(persons, message)
                _write_log(persons, message)

            #Send External Receiver
            if form.cleaned_data["external"]:
                if form.cleaned_data["extra_phones"]:
                    phones = form.cleaned_data["extra_phones"].split(',')
                    for phone in phones:
                        _send_single_sms(phone, message)
                        _write_single_log(message)

            #Send Non Member Receiver
            if form.cleaned_data["nonmembers"]:
                if form.cleaned_data["non_member"]:
                    phones = form.cleaned_data["non_member"]
                    for phone in phones:
                        person = nonmember.objects.get(id=int(phone.id))
                        _send_single_sms(phone, message)
                        _write_single_log(message,None,person)

            #Send Member Ulang Tahun
            if form.cleaned_data["ultah"]:
                if form.cleaned_data["ultah_today"]:
                    phones = form.cleaned_data["ultah_today"]
                    for phone in phones:
                        person = Person.objects.get(id=phone.id)
                        _send_single_sms(phone, message)
                        _write_single_log(message,None,person)

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        content_type="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },

        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:
            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'], instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response