Python django.middleware.csrf.get_token() Examples
The following are 30
code examples of django.middleware.csrf.get_token().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.middleware.csrf
, or try the search function
.
Example #1
Source File: context_processors.py From bioforum with MIT License | 7 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return token return {'csrf_token': SimpleLazyObject(_get_val)}
Example #2
Source File: __init__.py From PrivacyScore with GNU General Public License v3.0 | 6 votes |
def render_content_fragments(fragments, placeholders, request): csrf_token = get_token(request) if csrf_token is None: csrf_token = '' content = [] for fragment_type, fragment_content in fragments: if fragment_type == FragmentType.CONTENT: content.append(fragment_content) elif fragment_type == FragmentType.PLACEHOLDER: try: placeholder_content = str(placeholders[fragment_content]).encode() except KeyError: placeholder_content = b'' content.append(placeholder_content) elif fragment_type == FragmentType.CSRFTOKEN: content.append(csrf_token.encode()) else: raise ValueError('Invalid fragment type: {}'.format(fragment_type)) return b''.join(content)
Example #3
Source File: context_processors.py From python2017 with MIT License | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return force_text(token) return {'csrf_token': SimpleLazyObject(_get_val)}
Example #4
Source File: context_processors.py From openhgsenti with Apache License 2.0 | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return smart_text(token) return {'csrf_token': SimpleLazyObject(_get_val)}
Example #5
Source File: context_processors.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return smart_text(token) _get_val = lazy(_get_val, six.text_type) return {'csrf_token': _get_val() }
Example #6
Source File: views.py From dj4e-samples with MIT License | 6 votes |
def csrfform(request): response = """<p>CSRF Success guessing game...</p> <form method="POST"> <p><label for="guess">Input Guess</label> <input type="text" name="guess" size="40" id="guess"/></p> <input type="hidden" name="csrfmiddlewaretoken" value="__token__"/> <input type="submit"/> </form>""" token = get_token(request) response = response.replace('__token__', html.escape(token)) response += dumpdata('POST', request.POST) return HttpResponse(response) # Call as checkguess('42')
Example #7
Source File: context_processors.py From python with Apache License 2.0 | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return force_text(token) return {'csrf_token': SimpleLazyObject(_get_val)}
Example #8
Source File: context_processors.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return token return {'csrf_token': SimpleLazyObject(_get_val)}
Example #9
Source File: context_processors.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return smart_text(token) _get_val = lazy(_get_val, six.text_type) return {'csrf_token': _get_val()}
Example #10
Source File: api.py From c3nav with Apache License 2.0 | 5 votes |
def logout(self, request, *args, **kwargs): # django-rest-framework doesn't do this for logged out requests SessionAuthentication().enforce_csrf(request) if not request.user.is_authenticated: return ParseError(_('Not logged in.')) logout(request) return Response({ 'detail': _('Logout successful.'), 'csrf_token': csrf.get_token(request), })
Example #11
Source File: account.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def csrf(request): """Get the CSRF token for the authenticated user.""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) if ( request.user is None or not request.user.is_authenticated or not request.user.is_active ): return HttpResponseForbidden() token = get_token(request) # Don't mark the CSRF as used. If not done, Django will cycle the # CSRF and the returned CSRF will be un-usable. request.META.pop("CSRF_COOKIE_USED", None) return JsonResponse({"csrf": token})
Example #12
Source File: test_views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_login_csrf_rotate(self): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # The test client isn't used here as it's a test for middleware. req = HttpRequest() CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = LoginView.as_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': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = LoginView.as_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)
Example #13
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def csrf_token_error_handler(request, **kwargs): """This error handler accesses the CSRF token.""" template = Template(get_token(request)) return HttpResponse(template.render(Context()), status=599)
Example #14
Source File: test_views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_login_csrf_rotate(self): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # The test client isn't used here as it's a test for middleware. req = HttpRequest() CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = LoginView.as_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': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = LoginView.as_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)
Example #15
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def csrf_token_error_handler(request, **kwargs): """This error handler accesses the CSRF token.""" template = Template(get_token(request)) return HttpResponse(template.render(Context()), status=599)
Example #16
Source File: views.py From openstax-cms with GNU Affero General Public License v3.0 | 5 votes |
def send_contact_message(request): if request.method == 'POST': name = request.POST.get("from_name", "") from_name = name.replace(',', '') from_address = request.POST.get("from_address", "") from_string = '{} <{}>'.format(from_name, from_address) subject = request.POST.get("subject", "") message_body = request.POST.get("message_body", "") # Add subject: to_address to this dict to add a new email address. # Subject will map to the email being sent to to prevent misuse of our email server. mails = Mail.objects.all() emails = {mail.subject: mail.to_address for mail in mails} try: to_address = emails[subject].split(',') email = EmailMessage(subject, message_body, 'noreply@openstax.org', to_address, reply_to=[from_string]) email.send() except KeyError: logging.error("EMAIL FAILED TO SEND: subject:{}") if subject == "Bulk Order": # if this is a bulk order, send them to a special confirmation page return redirect('/confirmation/bulk-order') else: #otherwise, send them to the contact confirmation page return redirect('/confirmation/contact') # if this is not posting a message, let's send the csfr token back else: csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return JsonResponse(data)
Example #17
Source File: tests.py From openstax-cms with GNU Affero General Public License v3.0 | 5 votes |
def test_get_csrf_token(self): # testing that csrf token is returned on GET request to mail api response = self.client.get('/api/mail/send_mail/') request = response.wsgi_request csrf_token = csrf.get_token(request)
Example #18
Source File: csrf_update.py From iguana with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
def process_response(self, request, response): if isinstance(response, TemplateResponse) and response.template_name[0] in self.needs_update: content = response.content token = get_token(request) replace = b"name=\'csrfmiddlewaretoken\' value=\'" + token.encode() + b"\'" regex = re.compile(br"name=\'csrfmiddlewaretoken\'\s*value=\'\w*\'") response.content = re.sub(regex, replace, content) return response
Example #19
Source File: views.py From coursys with GNU General Public License v3.0 | 5 votes |
def render_column(self, row, column): instockclass = add_asset_display_class(row) if column == 'name': extra_string = '' if row.has_attachments(): extra_string += ' <i class="fa fa-paperclip" title="Attachment(s)"></i>' if row.has_records(): extra_string += ' <i class="fa fa-book" title="Record(s)"></i>' return row.name + extra_string if column == 'quantity': return str("<span class=" + instockclass + ">%s</span>" % row.quantity) elif column == 'last_modified': return str("<span class='sort'>%s</span>%s" % (row.last_modified, row.last_modified.strftime("%b %d, %Y"))) elif column == 'actions': return '<form class="lineform" method="POST" action=' +\ reverse('inventory:delete_asset', kwargs={'asset_id': row.id}) + '>' +\ '<input type="hidden" name="csrfmiddlewaretoken" value="' + get_token(self.request) + '">' +\ '<button type="submit" class="btn confirm-submit" title="Hide asset" data-submit-action="remove this asset">' +\ '<i class="fa fa-trash-o"></i>' +\ '</button>' +\ '</form>' +\ '<a class="lineform" href="' + reverse('inventory:add_change_record', kwargs={'asset_slug': row.slug}) +'">' +\ '<button type="submit" class="btn" title="Add change record">' +\ '<i class="fa fa-book"></i>' +\ '</button>' +\ '</a>' +\ '<a class="lineform" href="' + reverse('inventory:edit_asset', kwargs={'asset_slug': row.slug}) + '">' +\ '<button type="submit" class="btn" title="Edit asset">' +\ '<i class="fa fa-edit"></i>' +\ '</button>' +\ '</a>' +\ '<a class="lineform" href="' + reverse('inventory:view_asset', kwargs={'asset_slug': row.slug}) + '">' +\ '<button type="submit" class="btn" title="View asset">' +\ '<i class="fa fa-eye"></i>' +\ '</button>' +\ '</a>' else: return super(InventoryDataJSON, self).render_column(row, column)
Example #20
Source File: utils.py From python2017 with MIT License | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />', get_token(request))
Example #21
Source File: utils.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}">', get_token(request))
Example #22
Source File: api.py From c3nav with Apache License 2.0 | 5 votes |
def get_token(self, request, *args, **kwargs): # django-rest-framework doesn't do this for logged out requests SessionAuthentication().enforce_csrf(request) data = get_api_post_data(request) form = AuthenticationForm(request, data=data) if not form.is_valid(): raise ParseError(form.errors) token = form.user_cache.login_tokens.create() return Response({ 'token': token.get_token(), })
Example #23
Source File: api.py From c3nav with Apache License 2.0 | 5 votes |
def login(self, request, *args, **kwargs): # django-rest-framework doesn't do this for logged out requests SessionAuthentication().enforce_csrf(request) if request.user.is_authenticated: raise ParseError(_('Log out first.')) data = get_api_post_data(request) if 'token' in data: try: token = Token.get_by_token(data['token']) except Token.DoesNotExist: raise PermissionDenied(_('This token does not exist or is no longer valid.')) user = token.user elif 'username' in data: form = AuthenticationForm(request, data=data) if not form.is_valid(): raise ParseError(form.errors) user = form.user_cache else: raise ParseError(_('You need to send a token or username and password.')) login(request, user) return Response({ 'detail': _('Login successful.'), 'csrf_token': csrf.get_token(request), })
Example #24
Source File: api.py From c3nav with Apache License 2.0 | 5 votes |
def list(self, request, *args, **kwargs): return Response({ 'is_authenticated': request.user.is_authenticated, 'csrf_token': csrf.get_token(request), })
Example #25
Source File: utils.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />', get_token(request))
Example #26
Source File: utils.py From openhgsenti with Apache License 2.0 | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />', get_token(request))
Example #27
Source File: utils.py From bioforum with MIT License | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />', get_token(request))
Example #28
Source File: context_processors.py From django_microsoft_auth with MIT License | 5 votes |
def microsoft(request): """ Adds global template variables for microsoft_auth """ login_type = None if config.MICROSOFT_AUTH_LOGIN_TYPE == LOGIN_TYPE_XBL: login_type = _("Xbox Live") else: login_type = _("Microsoft") if config.DEBUG: # pragma: no branch try: current_domain = Site.objects.get_current(request).domain except Site.DoesNotExist: logger.warning( "\nWARNING:\nThe domain configured for the sites framework " "does not match the domain you are accessing Django with. " "Microsoft authentication may not work.\n" ) else: do_warning = get_scheme( request ) == "http" and not current_domain.startswith("localhost") if do_warning: # pragma: no branch logger.warning( "\nWARNING:\nYou are not using HTTPS. Microsoft " "authentication only works over HTTPS unless the hostname " "for your `redirect_uri` is `localhost`\n" ) # initialize Microsoft client using CSRF token as state variable signer = TimestampSigner() state = signer.sign(get_token(request)) microsoft = MicrosoftClient(state=state, request=request) auth_url = microsoft.authorization_url()[0] return { "microsoft_login_enabled": config.MICROSOFT_AUTH_LOGIN_ENABLED, "microsoft_authorization_url": mark_safe(auth_url), # nosec "microsoft_login_type_text": login_type, }
Example #29
Source File: utils.py From python with Apache License 2.0 | 5 votes |
def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />', get_token(request))
Example #30
Source File: video_calls.py From zulip with Apache License 2.0 | 5 votes |
def get_zoom_sid(request: HttpRequest) -> str: # This is used to prevent CSRF attacks on the Zoom OAuth # authentication flow. We want this value to be unpredictable and # tied to the session, but we don’t want to expose the main CSRF # token directly to the Zoom server. csrf.get_token(request) # Use 'mark_sanitized' to cause Pysa to ignore the flow of user controlled # data out of this function. 'request.META' is indeed user controlled, but # post-HMAC ouptut is no longer meaningfully controllable. return mark_sanitized( "" if getattr(request, "_dont_enforce_csrf_checks", False) else salted_hmac("Zulip Zoom sid", request.META["CSRF_COOKIE"]).hexdigest() )