def process_request(self, request): """ Add a CSRF token to the session for logged-in users. The token is available at request.csrf_token. """ if hasattr(request, 'csrf_token'): return if request.user.is_authenticated() and request.staff.is_authenticated(): if 'csrf_token' not in request.session: token = django_csrf._get_new_csrf_key() request.csrf_token = request.session['csrf_token'] = token else: request.csrf_token = request.session['csrf_token'] else: key = None token = '' if ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] token = cache.get(PREFIX + key, '') if ANON_ALWAYS: if not key: key = django_csrf._get_new_csrf_key() if not token: token = django_csrf._get_new_csrf_key() request._anon_csrf_key = key cache.set(PREFIX + key, token, ANON_TIMEOUT) request.csrf_token = token
def process_request(self, request): """ Add a CSRF token to the session for logged-in users. The token is available at request.csrf_token. """ if hasattr(request, 'csrf_token'): return if request.user.is_authenticated(): if self._has_valid_csrf(request): request.csrf_token = request.session['csrf_token'] else: token = Token.objects.create(owner=request.user).value request.csrf_token = request.session['csrf_token'] = token else: key = None token = '' if conf.ANON_COOKIE in request.COOKIES: key = request.COOKIES[conf.ANON_COOKIE] token = cache.get(prep_key(key), '') if conf.ANON_ALWAYS: if not key: key = django_csrf._get_new_csrf_key() if not token: token = django_csrf._get_new_csrf_key() request._anon_csrf_key = key cache.set(prep_key(key), token, conf.ANON_TIMEOUT) request.csrf_token = token
def process_request(self, request): """ Add a CSRF token to the session for logged-in users. The token is available at request.csrf_token. """ if hasattr(request, 'csrf_token'): return if request.user.is_authenticated(): if 'csrf_token' not in request.session: token = django_csrf._get_new_csrf_key() request.csrf_token = request.session['csrf_token'] = token else: request.csrf_token = request.session['csrf_token'] else: key = None token = '' if ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] token = cache.get(PREFIX + key, '') if ANON_ALWAYS: if not key: key = django_csrf._get_new_csrf_key() if not token: token = django_csrf._get_new_csrf_key() request._anon_csrf_key = key cache.set(PREFIX + key, token, ANON_TIMEOUT) request.csrf_token = token
def post(self, request, _backend): # pylint: disable=arguments-differ """ Handle POST requests to get a first-party access token. """ data = request.POST.copy() # log.info('=== AccessTokenExchangeBase ===') # log.info(data) log.error("=== AccessTokenExchangeBase ===") if data.get('is_linkedin_mobile', False): data['csrfmiddlewaretoken'] = _get_new_csrf_key() log.error(data) form = AccessTokenExchangeForm(request=request, oauth2_adapter=self.oauth2_adapter, data=data) # pylint: disable=no-member if not form.is_valid(): # log.info("=== form is not valid ===") log.error("form is not valid") log.error(form.errors) return self.error_response(form.errors) # pylint: disable=no-member user = form.cleaned_data["user"] scope = form.cleaned_data["scope"] client = form.cleaned_data["client"] return self.exchange_access_token(request, user, scope, client)
def test_disable_csrf(self): form = TestForm() helper = FormHelper() helper.disable_csrf = True html = render_crispy_form(form, helper, {'csrf_token': _get_new_csrf_key()}) self.assertFalse('csrf' in html)
def render(self, request): """Function that renders the form""" campaign_slug = self.options.get("campaign") if campaign_slug: from samklang_payment.models import DonationCampaign campaign = DonationCampaign.objects.get(slug=campaign_slug, payment_site=request.site.paymentsite) if campaign: suggestions = "-".join([str(s.amount) for s in campaign.donationsuggestion_set.all()]) default_amount = campaign.default_amount else: suggestions = "" default_amount = "" from django.middleware.csrf import _get_new_csrf_key from samklang_payment.forms import DonationForm form = DonationForm(initial={'amount': default_amount, 'suggestions': suggestions}) if not request.COOKIES: return _('<div class="error-message">You or your browser blocks our cookies. We need to use cookies to prevent cross site scripting attacks. The form will appear when cookies are allowed for this domain (%(site_domain)s). You will also need to allow cookies for the payment site (%(payment_site_domain)s).</div>') % {'site_domain': request.site.domain, 'payment_site_domain': NETS_PRODUCTION_HOST} if not request.COOKIES.get('csrftoken', None): request.META["CSRF_COOKIE"] = _get_new_csrf_key() return render_to_string('samklang_payment/donation_form_only.html', { 'form': form, 'form_action': reverse('payment-donation-create', args=[campaign_slug]), }, context_instance=RequestContext(request)) else: return ""
def invite(request, secret): invite = get_object_or_404(Invite, secret=secret) if request.method == 'POST': registration_form = UserCreationForm(request.POST) if invite.used_by == None and registration_form.is_valid(): user = registration_form.save() user.backend = 'django.contrib.auth.backends.ModelBackend' #TODO figure out what is the right thing to do here auth.login(request, user) invite.used_by = user invite.save() response = HttpResponseRedirect( reverse('banana.views.user', kwargs={'username': user.username})) # This is nasty but necessary because otherwise the session has no csrf cookie and thus cannot POST, which makes for a really bad user experience. if not "CSRF_COOKIE" in request.META: request.META["CSRF_COOKIE"] = _get_new_csrf_key() print 'Set new csrf cookie', request.META['CSRF_COOKIE'] response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age=60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE) return response else: registration_form = UserCreationForm() return render_to_response('person/invite.html', { 'registration_form': registration_form, 'invite': invite }, context_instance=RequestContext(request))
def test_disable_csrf(): form = SampleForm() helper = FormHelper() helper.disable_csrf = True html = render_crispy_form(form, helper, {'csrf_token': _get_new_csrf_key()}) assert 'csrf' not in html
def get_or_create_csrf_token(request): token = request.META.get('CSRF_COOKIE', None) if token is None: token = csrf._get_new_csrf_key() request.META['CSRF_COOKIE'] = token request.META['CSRF_COOKIE_USED'] = True return token
def invite(request, secret): invite = get_object_or_404(Invite, secret=secret) if request.method == "POST": registration_form = UserCreationForm(request.POST) if invite.used_by == None and registration_form.is_valid(): user = registration_form.save() user.backend = ( "django.contrib.auth.backends.ModelBackend" ) # TODO figure out what is the right thing to do here auth.login(request, user) invite.used_by = user invite.save() response = HttpResponseRedirect(reverse("banana.views.user", kwargs={"username": user.username})) # This is nasty but necessary because otherwise the session has no csrf cookie and thus cannot POST, which makes for a really bad user experience. if not "CSRF_COOKIE" in request.META: request.META["CSRF_COOKIE"] = _get_new_csrf_key() print "Set new csrf cookie", request.META["CSRF_COOKIE"] response.set_cookie( settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age=60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, ) return response else: registration_form = UserCreationForm() return render_to_response( "person/invite.html", {"registration_form": registration_form, "invite": invite}, context_instance=RequestContext(request), )
def test_enforce_csrf_works_with_token_in_cookie(self): ''' I can't figure out how to set up a request with a proper CSRF token. I think I need the same token in the posted data AND in either a request header or in the cookies. In this test I am trying to set it in the cookie for the authorized session. I do see it in client.cookies - but I am NOT seeing authenication info in the cookie, which makes me doubt the validity of the code. And it doesn't work. ''' # first set up some model instances we need user = User.objects.create_user(username='******', password='******') for name in ['blue', 'green', 'yellow', 'orange', 'red']: self.create_color(name) client = Client(enforce_csrf_checks=True) print('before login') print(self.client.cookies) client.login(username=user.username, password='******') print('after login') print(self.client.cookies) token = csrf._get_new_csrf_key() self.client.cookies['csrftoken'] = token print('after setting token') print(self.client.cookies) response = client.post('/', {'username': user.username, 'choice': 2, 'csrfmiddlewaretoken': token}) self.assertEqual(response.status_code, 200)
def test_uni_form_formset_with_helper_without_layout(self): template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form 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' TestFormSet = formset_factory(TestForm, extra=3) testFormSet = TestFormSet() c = Context({ 'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key() }) html = template.render(c) self.assertEqual(html.count('<form'), 1) self.assertEqual( html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) # Check formset management form self.assertTrue('form-TOTAL_FORMS' in html) self.assertTrue('form-INITIAL_FORMS' in html) self.assertTrue('form-MAX_NUM_FORMS' in html) self.assertTrue('class="uniForm formsets-that-rock"' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks">' in html) self.assertTrue('action="%s"' % reverse('simpleAction') 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_key()}) # 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
def _get_or_create_csrf_token(request): token = request.META.get('CSRF_COOKIE', None) if token is None: token = csrf._get_new_csrf_key() request.META['CSRF_COOKIE'] = token request.META['CSRF_COOKIE_USED'] = True token = "<input type='hidden' name='csrf_token' value='%s'" % (token) return token
def wrapper(request, *args, **kw): anon = not request.user.is_authenticated() if anon: if ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] token = cache.get(key) else: key = django_csrf._get_new_csrf_key() token = django_csrf._get_new_csrf_key() cache.set(key, token, ANON_TIMEOUT) request.csrf_token = token response = f(request, *args, **kw) if anon: # Set or reset the cache and cookie timeouts. response.set_cookie(ANON_COOKIE, key, max_age=ANON_TIMEOUT, httponly=True, secure=request.is_secure()) patch_vary_headers(response, ["Cookie"]) return response
def wrapper(request, *args, **kw): use_anon_cookie = not (request.user.is_authenticated() or conf.ANON_ALWAYS) if use_anon_cookie: if conf.ANON_COOKIE in request.COOKIES: key = request.COOKIES[conf.ANON_COOKIE] token = cache.get(prep_key(key)) or django_csrf._get_new_csrf_key() else: key = django_csrf._get_new_csrf_key() token = django_csrf._get_new_csrf_key() cache.set(prep_key(key), token, conf.ANON_TIMEOUT) request.csrf_token = token response = f(request, *args, **kw) if use_anon_cookie: # Set or reset the cache and cookie timeouts. response.set_cookie(conf.ANON_COOKIE, key, max_age=conf.ANON_TIMEOUT, httponly=True, secure=request.is_secure()) patch_vary_headers(response, ['Cookie']) return response
def process_request(self, request): """ If we are getting a POST that results in a decoded signed_request we shouldn't do CSRF protection. This is really so that we do not need to do @csrf_exempt on all views that interacts with Facebook. """ if request.FACEBOOK: request.META["CSRF_COOKIE"] = _get_new_csrf_key() request.csrf_processing_done = True
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_key() response.set_cookie('csrftoken', csrf_token) return response
def test_formset_layout(self): template = get_template_from_string(u""" {% 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' form_helper.add_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' ) ) ) TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({ 'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key() }) html = template.render(c) # Check form parameters self.assertEqual(html.count('<form'), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) # Check form layout self.assertTrue('Item 1' in html) self.assertTrue('Item 2' in html) self.assertTrue('Item 3' in html) self.assertEqual(html.count('Note for first form only'), 1) if settings.CRISPY_TEMPLATE_PACK == 'uni_form': self.assertEqual(html.count('formRow'), 3) else: self.assertEqual(html.count('row'), 3)
def test_formset_layout(settings): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() 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_key()}) # Check formset fields hidden_count = 4 # before Django 1.7 added MIN_NUM_FORM_COUNT assert html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ) == 1 assert html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ) == 1 assert html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ) == 1 if hasattr(forms.formsets, 'MIN_NUM_FORM_COUNT'): assert html.count( 'id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"' ) == 1 hidden_count += 1 assert html.count("hidden") == hidden_count # Check form structure assert html.count('<form') == 1 assert html.count("<input type='hidden' name='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 else: assert html.count('row') == 3
def wrapper(*args, **kwargs): request = args[0] expires = datetime.now() + timedelta(days=7) if request.COOKIES.get('user', None): _tk = request.COOKIES.get('user', None) else: _tk = _get_new_csrf_key() response = fn(*args, **kwargs) response.set_cookie('user', _tk, expires=expires) return response
def wrapper(request, *args, **kw): anon = not request.user.is_authenticated() if anon: if ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] token = cache.get(key) else: key = django_csrf._get_new_csrf_key() token = django_csrf._get_new_csrf_key() cache.set(key, token, ANON_TIMEOUT) request.csrf_token = token response = f(request, *args, **kw) if anon: # Set or reset the cache and cookie timeouts. response.set_cookie(ANON_COOKIE, key, max_age=ANON_TIMEOUT, httponly=True, secure=request.is_secure()) patch_vary_headers(response, ['Cookie']) return response
def get_or_create_csrf_token(request): try: csrf_token = _sanitize_token( request.COOKIES[django_settings.CSRF_COOKIE_NAME]) # Use same token next time except KeyError: csrf_token = _get_new_csrf_key() # Generate token and store it in the request, so it's # available to the view. request.META['CSRF_COOKIE'] = csrf_token request.META['CSRF_COOKIE_USED'] = True return csrf_token
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_key()}) html = template.render(c) assert 'csrfmiddlewaretoken' not in html
def test_CSRF_token_GET_form(): form_helper = FormHelper() form_helper.form_method = 'GET' template = get_template_from_string(""" {% load crispy_forms_tags %} {% crispy form form_helper %} """) c = Context({'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) assert "<input type='hidden' name='csrfmiddlewaretoken'" not in html
def test_csrf_token_GET_form(self): form_helper = FormHelper() form_helper.form_method = 'GET' template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form form form_helper %} """) c = Context({'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertFalse("<input type='hidden' name='csrfmiddlewaretoken'" in html)
def wrapper(request, *args, **kwargs): if request.method == "GET": csrf_token = _get_new_csrf_key() request.csrf_processing_done = False request.META['CSRF_COOKIE'] = csrf_token request.META['CSRF_COOKIE_USED'] = True kwargs["csrf_token"] = csrf_token ret = func(request, *args, **kwargs) return ret else: raise CsrfWrapperException("csrf 只能装饰在GET方法上")
def test_CSRF_token_GET_form(self): form_helper = FormHelper() form_helper.form_method = "GET" template = get_template_from_string( u""" {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": TestForm(), "form_helper": form_helper, "csrf_token": _get_new_csrf_key()}) html = template.render(c) self.assertFalse("<input type='hidden' name='csrfmiddlewaretoken'" in html)
def test_CSRF_token_POST_form(): form_helper = FormHelper() template = get_template_from_string(""" {% 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': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) assert "<input type='hidden' name='csrfmiddlewaretoken'" in html
def wrapper(request, *args, **kw): use_anon_cookie = not (request.user.is_authenticated() or conf.ANON_ALWAYS) if use_anon_cookie: if conf.ANON_COOKIE in request.COOKIES: key = request.COOKIES[conf.ANON_COOKIE] token = cache.get( prep_key(key)) or django_csrf._get_new_csrf_key() else: key = django_csrf._get_new_csrf_key() token = django_csrf._get_new_csrf_key() cache.set(prep_key(key), token, conf.ANON_TIMEOUT) request.csrf_token = token response = f(request, *args, **kw) if use_anon_cookie: # Set or reset the cache and cookie timeouts. response.set_cookie(conf.ANON_COOKIE, key, max_age=conf.ANON_TIMEOUT, httponly=True, secure=request.is_secure()) patch_vary_headers(response, ['Cookie']) return response
def set_csrf_cookie(self): """ Sets a unique CSRF cookie for subsequent requests to use. Returns the new cookie's value. """ self.cookies[settings.CSRF_COOKIE_NAME] = csrf._get_new_csrf_key() self.cookies[settings.CSRF_COOKIE_NAME].update({ "max_age": 60 * 60 * 24 * 7 * 52, "domain": settings.CSRF_COOKIE_DOMAIN, "path": settings.CSRF_COOKIE_PATH, "secure": settings.CSRF_COOKIE_SECURE, "httponly": settings.CSRF_COOKIE_HTTPONLY}) return self.cookies.get(settings.CSRF_COOKIE_NAME).value
def test_CSRF_token_POST_form(self): form_helper = FormHelper() template = get_template_from_string( u""" {% load uni_form_tags %} {% uni_form 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": TestForm(), "form_helper": form_helper, "csrf_token": _get_new_csrf_key()}) html = template.render(c) self.assertTrue("<input type='hidden' name='csrfmiddlewaretoken'" in html)
def get_fb_user_canvas(request): """ Attempt to find a user using a signed_request (canvas). """ data = get_signed_request_data(request) if data: if request.method == 'POST': # If this is requset method is POST then prevent rising err 403 # from Django CSRF middleware request.META["CSRF_COOKIE"] = _get_new_csrf_key() request.csrf_processing_done = True if data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def get_fb_user_canvas(request): """ Attempt to find a user using a signed_request (canvas). """ data = get_signed_request_data(request) if data: if request.method == "POST": # If this is requset method is POST then prevent rising err 403 # from Django CSRF middleware request.META["CSRF_COOKIE"] = _get_new_csrf_key() request.csrf_processing_done = True if data.get("user_id"): fb_user = data["user"] fb_user["method"] = "canvas" fb_user["uid"] = data["user_id"] fb_user["access_token"] = data["oauth_token"] return fb_user
def artificial_login(**credentials): from django.contrib.auth import authenticate, login cookies = SimpleCookie() user = authenticate(**credentials) engine = import_module(settings.SESSION_ENGINE) # Create a fake request that goes through request middleware request = WSGIRequest({ 'HTTP_COOKIE': cookies.output(header='', sep=';'), 'PATH_INFO': str('/'), 'REMOTE_ADDR': str('127.0.0.1'), 'REQUEST_METHOD': str('GET'), 'SCRIPT_NAME': str(''), 'SERVER_NAME': str('testserver'), 'SERVER_PORT': str('80'), 'SERVER_PROTOCOL': str('HTTP/1.1'), 'wsgi.version': (1, 0), 'wsgi.url_scheme': str('http'), 'wsgi.input': BytesIO(), 'wsgi.errors': BytesIO(), 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, }) request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } cookies[session_cookie].update(cookie_data) return { session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key(), }
def artificial_login(**credentials): from django.contrib.auth import authenticate, login cookies = SimpleCookie() user = authenticate(**credentials) engine = import_module(settings.SESSION_ENGINE) # Create a fake request that goes through request middleware request = WSGIRequest({ "HTTP_COOKIE": cookies.output(header="", sep=";"), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": BytesIO(), "wsgi.errors": BytesIO(), "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, }) request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } cookies[session_cookie].update(cookie_data) return { session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key(), }
def test_csrf_token_POST_form(self): form_helper = FormHelper() template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form 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 # reads to put a hidden input in > django.template.defaulttags.CsrfTokenNode # This way we don't need to use Django's client, have a test_app and urls # I like self-contained tests :) CSRF could be any number, we don't care c = Context({'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertTrue("<input type='hidden' name='csrfmiddlewaretoken'" in html)
def test_CSRF_token_GET_form(self): form_helper = FormHelper() form_helper.form_method = 'GET' template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form form form_helper %} """) c = Context({ 'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key() }) html = template.render(c) self.assertFalse( "<input type='hidden' name='csrfmiddlewaretoken'" in html)
def get_or_create_csrf_token(request): from django.middleware import csrf token = None try: token = request.META.get('CSRF_COOKIE', None) except Exception as e: print(e) pass if token is None: token = csrf._get_new_csrf_key() try: request.META['CSRF_COOKIE'] = token request.META['CSRF_COOKIE_USED'] = True except Exception as e: print(e) pass print(token) return token
def process_request(self, request): """ Add a CSRF token to the session for logged-in users. The token is available at request.csrf_token. """ if hasattr(request, "csrf_token"): return if request.user.is_authenticated(): if "csrf_token" not in request.session: token = django_csrf._get_new_csrf_key() request.csrf_token = request.session["csrf_token"] = token else: request.csrf_token = request.session["csrf_token"] elif ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] request.csrf_token = cache.get(key, "") else: request.csrf_token = ""
def process_request(self, request): """ Add a CSRF token to the session for logged-in users. The token is available at request.csrf_token. """ if hasattr(request, 'csrf_token'): return if request.user.is_authenticated(): if 'csrf_token' not in request.session: token = django_csrf._get_new_csrf_key() request.csrf_token = request.session['csrf_token'] = token else: request.csrf_token = request.session['csrf_token'] elif ANON_COOKIE in request.COOKIES: key = request.COOKIES[ANON_COOKIE] request.csrf_token = cache.get(key, '') else: request.csrf_token = ''
def get_fb_user_canvas(request): """ Attempt to find a user using a signed_request (canvas). """ signed_request = request.REQUEST.get('signed_request') if signed_request: data = facebook.parse_signed_request(signed_request, settings.SECRET_KEY) if data: if request.method == 'POST': # If this is requset method is POST then prevent rising err 403 # from Django CSRF middleware request.META["CSRF_COOKIE"] = _get_new_csrf_key() request.csrf_processing_done = True if data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def test_enforce_csrf_works_with_token_in_header(self): ''' I can't figure out how to set up a request with a proper CSRF token. I think I need the same token in the posted data AND in either a request header or in the cookies. In this test I am trying to set it in the request headers per the docs: https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax ''' # first set up some model instances we need user = User.objects.create_user(username='******', password='******') for name in ['blue', 'green', 'yellow', 'orange', 'red']: self.create_color(name) token = csrf._get_new_csrf_key() # client = Client(enforce_csrf_checks=True, HTTP_X_CSRFTOKEN=token, HTTP_REFERER='http://test.example.com/') client = Client(enforce_csrf_checks=True, HTTP_X_CSRFTOKEN=token) # pprint(client.__dict__) response = client.post('/', {'username': user.username, 'choice': 2, 'csrfmiddlewaretoken': token}) # pprint(response.__dict__) self.assertEqual(response.status_code, 200)
def restore_csrf_token(request, storage=None): """ Given the request and a the context used during the second render phase, this wil check if there is a CSRF cookie and restores if needed, to counteract the way the CSRF framework invalidates the CSRF token after each request/response cycle. """ if storage is None: storage = {} try: if not request.META.get("CSRF_COOKIE", False): request.META["CSRF_COOKIE"] = request.COOKIES[django_settings.CSRF_COOKIE_NAME] except KeyError: csrf_token = storage.get('csrf_token', None) if csrf_token: # if the context has a cached csrf token generate a new token # otherwise all users will get the same csrf token assigned csrf_token = _get_new_csrf_key() request.META["CSRF_COOKIE"] = csrf_token storage['csrf_token'] = csrf_token return storage
def manual_csrf_check(request): """ Performs a CSRF check for a specific request. Useful for in-view CSRF checks. Returns an HTTP response in case of CSRF failure. """ try: csrf_token = _sanitize_token( request.COOKIES[settings.CSRF_COOKIE_NAME] ) request.META['CSRF_COOKIE'] = csrf_token except KeyError: csrf_token = None request.META["CSRF_COOKIE"] = _get_new_csrf_key() if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): if request.is_secure(): referer = request.META.get('HTTP_REFERER') if referer is None: return middleware._reject(request, REASON_NO_REFERER) good_referer = 'https://%s/' % request.get_host() if not same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) return middleware._reject(request, reason) if csrf_token is None: return middleware._reject(request, REASON_NO_CSRF_COOKIE) request_csrf_token = "" if request.method == "POST": request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') if request_csrf_token == "": request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): return middleware._reject(request, REASON_BAD_TOKEN)
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_key() }) html = template.render(c) assert html.count('<form') == 1 assert html.count("<input type='hidden' name='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
def csrf(request): return JsonResponse({"token": _get_new_csrf_key()})
def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, 'csrf_processing_done', False): return None try: csrf_token = django_csrf._sanitize_token( request.COOKIES[settings.CSRF_COOKIE_NAME]) # Use same token next time request.META['CSRF_COOKIE'] = csrf_token except KeyError: csrf_token = None # Generate token and store it in the request, so it's # available to the view. request.META["CSRF_COOKIE"] = django_csrf._get_new_csrf_key() # Wait until request.META["CSRF_COOKIE"] has been manipulated before # bailing out, so that get_token still works if getattr(callback, 'csrf_exempt', False): return None # Assume that anything not defined as 'safe' by RFC2616 needs protection if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): if getattr(request, '_dont_enforce_csrf_checks', False): # Mechanism to turn off CSRF checks for test suite. # It comes after the creation of CSRF cookies, so that # everything else continues to work exactly the same # (e.g. cookies are sent, etc.), but before any # branches that call reject(). return self._accept(request) if request.is_secure(): # Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM and the session-independent # nonce we're using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. referer = force_text(request.META.get('HTTP_REFERER'), strings_only=True, errors='replace') if referer is None: return self._reject(request, django_csrf.REASON_NO_REFERER) # Here we generate a list of all acceptable HTTP referers, # including the current host since that has been validated # upstream. good_hosts = list(settings.CSRF_TRUSTED_ORIGINS) # Note that request.get_host() includes the port. good_hosts.append(request.get_host()) good_referers = [ 'https://{0}/'.format(host) for host in good_hosts ] if not any( same_origin(referer, host) for host in good_referers): reason = REASON_BAD_REFERER % referer return self._reject(request, reason) if csrf_token is None: # No CSRF cookie. For POST requests, we insist on a CSRF cookie, # and in this way we can avoid all CSRF attacks, including login # CSRF. return self._reject(request, django_csrf.REASON_NO_CSRF_COOKIE) # Check non-cookie token for match. request_csrf_token = "" if request.method == "POST": try: request_csrf_token = request.POST.get( 'csrfmiddlewaretoken', '') except IOError: # Handle a broken connection before we've completed reading # the POST data. process_view shouldn't raise any # exceptions, so we'll ignore and serve the user a 403 # (assuming they're still listening, which they probably # aren't because of the error). pass if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX, # and possible for PUT/DELETE. request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): return self._reject(request, django_csrf.REASON_BAD_TOKEN) return self._accept(request)
if k != exclude_key: if values: values += '&' values += k + '=' + v return values def get_or_create_csrf_token(request): from django.middleware import csrf token = None try: token = request.META.get('CSRF_COOKIE', None) except Exception, e: print e pass if token is None: token = csrf._get_new_csrf_key() try: request.META['CSRF_COOKIE'] = token request.META['CSRF_COOKIE_USED'] = True except Exception, e: print e pass print token return token def paginator_page_cutter(page_range, current_page): page_count = len(page_range) if page_count <= 11: return page_range start_page = current_page - 5
def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, 'csrf_processing_done', False): return None try: request.META["CSRF_COOKIE"] = _sanitize_token( request.COOKIES[settings.CSRF_COOKIE_NAME]) cookie_is_new = False except KeyError: request.META["CSRF_COOKIE"] = _get_new_csrf_key() cookie_is_new = True if getattr(callback, 'csrf_exempt', False): return None if request.method == 'POST': if getattr(request, '_dont_enforce_csrf_checks', False): return self._accept(request) # let initial signed requests pass if 'signed_request' in request.POST: post = request.POST.copy() post.pop('signed_request') if len(post) == 0: return self._accept(request) if request.is_secure() and getattr(settings, 'HTTPS_REFERER_REQUIRED', True): referer = request.META.get('HTTP_REFERER') if referer is None: logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path), extra={ 'status_code': 403, 'request': request, }) return self._reject(request, REASON_NO_REFERER) # Note that request.get_host() includes the port good_referer = 'https://%s/' % request.get_host() if not same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) logger.warning('Forbidden (%s): %s' % (reason, request.path), extra={ 'status_code': 403, 'request': request, }) return self._reject(request, reason) if cookie_is_new: try: session_id = request.COOKIES[settings.SESSION_COOKIE_NAME] csrf_token = _make_legacy_session_token(session_id) except KeyError: logger.warning('Forbidden (%s): %s' % (REASON_NO_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, }) return self._reject(request, REASON_NO_COOKIE) else: csrf_token = request.META["CSRF_COOKIE"] # check incoming token request_csrf_token = request.POST.get('csrfmiddlewaretoken', None) if not request_csrf_token: request_csrf_token = request.POST.get('state', '') if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): if cookie_is_new: # probably a problem setting the CSRF cookie logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, }) return self._reject(request, REASON_NO_CSRF_COOKIE) else: logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path), extra={ 'status_code': 403, 'request': request, }) return self._reject(request, REASON_BAD_TOKEN) return self._accept(request)
def test_formset_layout(self): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() 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_key()}) # Check formset fields django_version = django.VERSION[:3] hidden_count = 4 # before Django 1.7 added MIN_NUM_FORM_COUNT if django_version < (1, 5): self.assertEqual( html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ), 1) self.assertEqual( html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ), 1) if (django_version >= (1, 4) and django_version < (1, 4, 4)) or django_version < (1, 3, 6): self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ), 1) self.assertEqual( html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ), 1) self.assertEqual( html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ), 1) if hasattr(forms.formsets, 'MIN_NUM_FORM_COUNT'): self.assertEqual( html.count( 'id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"' ), 1) hidden_count += 1 self.assertEqual(html.count("hidden"), hidden_count) # Check form structure self.assertEqual(html.count('<form'), 1) self.assertEqual( html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) # Check form layout self.assertTrue('Item 1' in html) self.assertTrue('Item 2' in html) self.assertTrue('Item 3' in html) self.assertEqual(html.count('Note for first form only'), 1) if self.current_template_pack == 'uni_form': self.assertEqual(html.count('formRow'), 3) else: self.assertEqual(html.count('row'), 3)