Python django.utils.http.is_safe_url() Examples
The following are 30
code examples of django.utils.http.is_safe_url().
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.utils.http
, or try the search function
.
Example #1
Source File: views.py From simple-django-login-and-register with BSD 3-Clause "New" or "Revised" License | 7 votes |
def form_valid(self, form): request = self.request # If the test cookie worked, go ahead and delete it since its no longer needed if request.session.test_cookie_worked(): request.session.delete_test_cookie() # The default Django's "remember me" lifetime is 2 weeks and can be changed by modifying # the SESSION_COOKIE_AGE settings' option. if settings.USE_REMEMBER_ME: if not form.cleaned_data['remember_me']: request.session.set_expiry(0) login(request, form.user_cache) redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME)) url_is_safe = is_safe_url(redirect_to, allowed_hosts=request.get_host(), require_https=request.is_secure()) if url_is_safe: return redirect(redirect_to) return redirect(settings.LOGIN_REDIRECT_URL)
Example #2
Source File: views.py From djacket with MIT License | 6 votes |
def user_login(request): """ View for logging users in. """ redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, '')) login_form = AuthenticationForm(request, data=request.POST) if login_form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=REDIRECT_FIELD_NAME, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL # Okay, security check complete. Log the user in. auth_login(request, login_form.get_user()) return redirect(settings.LOGIN_REDIRECT_URL if redirect_to == '' else redirect_to) else: return render(request, 'index.html', {'login_form': login_form, 'display': 'block', 'active': 'login'})
Example #3
Source File: views.py From esdc-ce with Apache License 2.0 | 6 votes |
def setlang(request): """ Sets a user's language preference and redirects to a given URL or, by default, back to the previous page. """ next = request.GET.get('next', None) if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = redirect(next) lang_code = request.GET.get('language', None) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN) return response
Example #4
Source File: views.py From python2017 with MIT License | 6 votes |
def get_next_page(self): if self.next_page is not None: next_page = resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) else: next_page = self.next_page if (self.redirect_field_name in self.request.POST or self.redirect_field_name in self.request.GET): next_page = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) # Security check -- Ensure the user-originating redirection URL is # safe. if not url_is_safe: next_page = self.request.path return next_page
Example #5
Source File: viste.py From jorvik with GNU General Public License v3.0 | 6 votes |
def done(self, form_list, **kwargs): """ Login the user and redirect to the desired page. """ login(self.request, self.get_user()) redirect_to = self.request.GET.get(self.redirect_field_name, '') if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) if self.get_user().richiedi_attivazione_2fa: redirect_to = resolve_url(settings.TWO_FACTOR_PROFILE) device = getattr(self.get_user(), 'otp_device', None) if device: signals.user_verified.send(sender=__name__, request=self.request, user=self.get_user(), device=device) return redirect(redirect_to)
Example #6
Source File: views.py From anytask with MIT License | 6 votes |
def set_user_language(request): next = request.REQUEST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get('language', None) if 'ref' not in next: ref = urlparse(request.POST.get('referrer', next)) response = HttpResponseRedirect('?ref='.join([next, ref.path])) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) user = request.user if user.is_authenticated(): user_profile = user.profile user_profile.language = lang_code user_profile.save() return response
Example #7
Source File: i18n.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next = request.REQUEST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = http.HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get('language', None) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response
Example #8
Source File: views.py From peering-manager with Apache License 2.0 | 6 votes |
def get_return_url(self, request, obj=None): # First, see if `return_url` was specified as a query parameter or form data. # Use this URL only if it's considered safe. query_param = request.GET.get("return_url") or request.POST.get("return_url") if query_param and is_safe_url( url=query_param, allowed_hosts=request.get_host() ): return query_param # Next, check if the object being modified (if any) has an absolute URL. elif obj is not None and obj.pk and hasattr(obj, "get_absolute_url"): return obj.get_absolute_url() # Fall back to the default URL (if specified) for the view. elif self.default_return_url is not None: return reverse(self.default_return_url) # If all else fails, return home. Ideally this should never happen. return reverse("home")
Example #9
Source File: views.py From django-notify-x with MIT License | 6 votes |
def notification_redirect(request, ctx): """ Helper to handle HTTP response after an action is performed on notification :param request: HTTP request context of the notification :param ctx: context to be returned when a AJAX call is made. :returns: Either JSON for AJAX or redirects to the calculated next page. """ if request.is_ajax(): return JsonResponse(ctx) else: next_page = request.POST.get('next', reverse('notifications:all')) if not ctx['success']: return HttpResponseBadRequest(ctx['msg']) if is_safe_url(next_page): return HttpResponseRedirect(next_page) else: return HttpResponseRedirect(reverse('notifications:all'))
Example #10
Source File: views.py From bioforum with MIT License | 6 votes |
def get_next_page(self): if self.next_page is not None: next_page = resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) else: next_page = self.next_page if (self.redirect_field_name in self.request.POST or self.redirect_field_name in self.request.GET): next_page = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) # Security check -- Ensure the user-originating redirection URL is # safe. if not url_is_safe: next_page = self.request.path return next_page
Example #11
Source File: views.py From django-sudo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def dispatch(self, request): redirect_to = request.GET.get(REDIRECT_FIELD_NAME, REDIRECT_URL) # Make sure we're not redirecting to other sites if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(REDIRECT_URL) if request.is_sudo(): return HttpResponseRedirect(redirect_to) if request.method == "GET": request.session[REDIRECT_TO_FIELD_NAME] = redirect_to context = { "form": self.form_class(request.user, request.POST or None), "request": request, REDIRECT_FIELD_NAME: redirect_to, } if self.handle_sudo(request, redirect_to, context): return self.grant_sudo_privileges(request, redirect_to) if self.extra_context is not None: context.update(self.extra_context) return TemplateResponse(request, self.template_name, context)
Example #12
Source File: views.py From django-u2f with BSD 2-Clause "Simplified" License | 6 votes |
def form_valid(self, form): user = form.get_user() if not self.requires_two_factor(user): # no keys registered, use single-factor auth return super(U2FLoginView, self).form_valid(form) else: self.request.session['u2f_pre_verify_user_pk'] = user.pk self.request.session['u2f_pre_verify_user_backend'] = user.backend verify_url = reverse('u2f:verify-second-factor') redirect_to = self.request.POST.get(auth.REDIRECT_FIELD_NAME, self.request.GET.get(auth.REDIRECT_FIELD_NAME, '')) params = {} if is_safe_url(url=redirect_to, allowed_hosts=self.request.get_host()): params[auth.REDIRECT_FIELD_NAME] = redirect_to if self.is_admin: params['admin'] = 1 if params: verify_url += '?' + urlencode(params) return HttpResponseRedirect(verify_url)
Example #13
Source File: views.py From zentral with Apache License 2.0 | 6 votes |
def post(self, request, *args, **kwargs): realm = get_object_or_404(Realm, pk=kwargs["pk"], enabled_for_login=True) callback = "realms.utils.login_callback" callback_kwargs = {} next_url = request.POST.get("next") if next_url and is_safe_url(url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure()): callback_kwargs["next_url"] = next_url redirect_url = None try: redirect_url = realm.backend_instance.initialize_session(callback, **callback_kwargs) except Exception: logger.exception("Could not get realm %s redirect URL", realm.pk) else: if redirect_url: return HttpResponseRedirect(redirect_url) else: raise ValueError("Empty realm {} redirect URL".format(realm.pk))
Example #14
Source File: tasks.py From online-judge with GNU Affero General Public License v3.0 | 6 votes |
def task_status(request, task_id): try: UUID(task_id) except ValueError: raise Http404() redirect = request.GET.get('redirect') if not is_safe_url(redirect, allowed_hosts={request.get_host()}): redirect = None status = get_task_status(task_id) if status['code'] == 'SUCCESS' and redirect: return HttpResponseRedirect(redirect) return render(request, 'task_status.html', { 'task_id': task_id, 'task_status': json.dumps(status), 'message': request.GET.get('message', ''), 'redirect': redirect or '', })
Example #15
Source File: views.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def set_locale(request): """ Redirect to the referrer URL while setting the chosen language in the session. The new language needs to be specified in the request body as `new_locale`. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. Based on `django.views.i18n.set_language` """ next = request.POST.get("next", "/") if not is_safe_url( url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure() ): next = "/" response = HttpResponseRedirect(next) locale = request.POST.get("new_locale") if is_supported(locale): request.locale_id = locale # Save current locale in a cookie. set_language_cookie(response, locale) if request.user.is_authenticated: request.user.user_profile.locale_id = locale request.user.user_profile.save(update_fields=["locale_id"]) return response
Example #16
Source File: views.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def get_next_page(self): if self.next_page is not None: next_page = resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) else: next_page = self.next_page if (self.redirect_field_name in self.request.POST or self.redirect_field_name in self.request.GET): next_page = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) # Security check -- Ensure the user-originating redirection URL is # safe. if not url_is_safe: next_page = self.request.path return next_page
Example #17
Source File: pages.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def lock(request, page_id): # Get the page page = get_object_or_404(Page, id=page_id).specific # Check permissions if not page.permissions_for_user(request.user).can_lock(): raise PermissionDenied # Lock the page if not page.locked: page.locked = True page.locked_by = request.user page.locked_at = timezone.now() page.save() # Redirect redirect_to = request.POST.get('next', None) if redirect_to and is_safe_url(url=redirect_to, allowed_hosts={request.get_host()}): return redirect(redirect_to) else: return redirect('wagtailadmin_explore', page.get_parent().id)
Example #18
Source File: views.py From django-mfa with MIT License | 6 votes |
def form_valid(self, form, forms): if not form.validate_second_factor(): return self.form_invalid(forms) del self.request.session['u2f_pre_verify_user_pk'] del self.request.session['u2f_pre_verify_user_backend'] self.request.session['verfied_otp'] = True self.request.session['verfied_u2f'] = True auth.login(self.request, self.user) redirect_to = self.request.POST.get(auth.REDIRECT_FIELD_NAME, self.request.GET.get(auth.REDIRECT_FIELD_NAME, '')) if not is_safe_url(url=redirect_to, allowed_hosts=self.request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
Example #19
Source File: pages.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def unlock(request, page_id): # Get the page page = get_object_or_404(Page, id=page_id).specific # Check permissions if not page.permissions_for_user(request.user).can_unlock(): raise PermissionDenied # Unlock the page if page.locked: page.locked = False page.locked_by = None page.locked_at = None page.save() messages.success(request, _("Page '{0}' is now unlocked.").format(page.get_admin_display_title()), extra_tags='unlock') # Redirect redirect_to = request.POST.get('next', None) if redirect_to and is_safe_url(url=redirect_to, allowed_hosts={request.get_host()}): return redirect(redirect_to) else: return redirect('wagtailadmin_explore', page.get_parent().id)
Example #20
Source File: views.py From SOMS with GNU General Public License v3.0 | 6 votes |
def logout(request, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Logs out the user and displays 'You are logged out' message. """ Message.objects.create(type=u'用户退出', user=request.user, action=u'用户退出', action_ip=UserIP(request), content='用户退出 %s' % request.user) auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return HttpResponseRedirect('/')
Example #21
Source File: i18n.py From python2017 with MIT License | 5 votes |
def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next = request.POST.get('next', request.GET.get('next')) if ((next or not request.is_ajax()) and not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())): next = request.META.get('HTTP_REFERER') if next: next = urlunquote(next) # HTTP_REFERER may be encoded. if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()): next = '/' response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204) if request.method == 'POST': lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next: next_trans = translate_url(next, lang_code) if next_trans != next: response = http.HttpResponseRedirect(next_trans) if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code else: response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, ) return response
Example #22
Source File: i18n.py From python with Apache License 2.0 | 5 votes |
def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next = request.POST.get('next', request.GET.get('next')) if ((next or not request.is_ajax()) and not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())): next = request.META.get('HTTP_REFERER') if next: next = urlunquote(next) # HTTP_REFERER may be encoded. if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()): next = '/' response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204) if request.method == 'POST': lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next: next_trans = translate_url(next, lang_code) if next_trans != next: response = http.HttpResponseRedirect(next_trans) if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code else: response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, ) return response
Example #23
Source File: __init__.py From kpi with GNU Affero General Public License v3.0 | 5 votes |
def one_time_login(request): """ If the request provides a key that matches a OneTimeAuthenticationKey object, log in the User specified in that object and redirect to the location specified in the 'next' parameter """ try: key = request.POST['key'] except KeyError: return HttpResponseBadRequest(_('No key provided')) try: next_ = request.GET['next'] except KeyError: next_ = None if not next_ or not is_safe_url(url=next_, host=request.get_host()): next_ = resolve_url(settings.LOGIN_REDIRECT_URL) # Clean out all expired keys, just to keep the database tidier OneTimeAuthenticationKey.objects.filter( expiry__lt=datetime.datetime.now()).delete() with transaction.atomic(): try: otak = OneTimeAuthenticationKey.objects.get( key=key, expiry__gte=datetime.datetime.now() ) except OneTimeAuthenticationKey.DoesNotExist: return HttpResponseBadRequest(_('Invalid or expired key')) # Nevermore otak.delete() # The request included a valid one-time key. Log in the associated user user = otak.user user.backend = settings.AUTHENTICATION_BACKENDS[0] login(request, user) return HttpResponseRedirect(next_) # TODO Verify if it's still used
Example #24
Source File: views.py From django-u2f with BSD 2-Clause "Simplified" License | 5 votes |
def get_success_url(self): if 'next' in self.request.GET and is_safe_url(self.request.GET['next']): return self.request.GET['next'] else: return super(AddTOTPDeviceView, self).get_success_url()
Example #25
Source File: views.py From django-u2f with BSD 2-Clause "Simplified" License | 5 votes |
def form_valid(self, form, forms): if not form.validate_second_factor(): return self.form_invalid(forms) del self.request.session['u2f_pre_verify_user_pk'] del self.request.session['u2f_pre_verify_user_backend'] auth.login(self.request, self.user) redirect_to = self.request.POST.get(auth.REDIRECT_FIELD_NAME, self.request.GET.get(auth.REDIRECT_FIELD_NAME, '')) if not is_safe_url(url=redirect_to, allowed_hosts=self.request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
Example #26
Source File: views.py From django-u2f with BSD 2-Clause "Simplified" License | 5 votes |
def get_success_url(self): if 'next' in self.request.GET and is_safe_url(self.request.GET['next']): return self.request.GET['next'] else: return super(AddKeyView, self).get_success_url()
Example #27
Source File: view_partials.py From callisto-core with GNU Affero General Public License v3.0 | 5 votes |
def _passphrase_next_url(self, request): next_url = None if "next" in request.GET: if re.search(r"^/[\W/-]*", request.GET["next"]): if is_safe_url(request.GET["next"]): next_url = request.GET["next"] return next_url
Example #28
Source File: views.py From openhgsenti with Apache License 2.0 | 5 votes |
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, extra_context=None): """ Logs out the user and displays 'You are logged out' message. """ auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out') } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)
Example #29
Source File: views.py From python2017 with MIT License | 5 votes |
def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = is_safe_url( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) return redirect_to if url_is_safe else ''
Example #30
Source File: view_partials.py From callisto-core with GNU Affero General Public License v3.0 | 5 votes |
def get_success_url(self): next_page = self.request.GET.get("next", None) if next_page and is_safe_url(next_page, self.request.get_host()): return next_page else: return super().get_success_url()