我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.utils.http.is_safe_url()。
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is None: messages.error(request, _('No user account matches the entered credentials.')) return redirect('common:login') if not user.is_active: messages.error(request, _('User account is deactivated.')) return redirect('common:login') login(request, user) url = urllib.parse.unquote(request.GET.get('next', '')) if url and is_safe_url(url, request.get_host()): return redirect(url) return redirect('/')
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is None: messages.error(request, _('No user account matches the entered credentials.')) return redirect('backoffice:login') if not user.is_active: messages.error(request, _('User account is deactivated.')) return redirect('backoffice:login') if not is_backoffice_user(user): messages.error(request, _('User does not have permission to access backoffice data.')) return redirect('backoffice:login') login(request, user) url = request.GET.get('next') if url and is_safe_url(url, request.get_host()): return redirect(url) return redirect('backoffice:main')
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
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'})
def get(self, request, *args, **kwargs): url = request.GET.get('next', request.META.get('HTTP_REFERER', '/')) url = url if is_safe_url(url, host=request.get_host()) else '/' resp = HttpResponseRedirect(url) locale = request.GET.get('locale') if locale in [lc for lc, ll in settings.LANGUAGES]: if request.user.is_authenticated: request.user.locale = locale request.user.save() max_age = 10 * 365 * 24 * 60 * 60 resp.set_cookie(settings.LANGUAGE_COOKIE_NAME, locale, max_age=max_age, expires=(datetime.utcnow() + timedelta(seconds=max_age)).strftime( '%a, %d-%b-%Y %H:%M:%S GMT'), domain=settings.SESSION_COOKIE_DOMAIN) with override(locale): messages.success(request, phrases.cfp.locale_change_success) return resp
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.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 = redirect(next) lang_code = request.REQUEST.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
def logout(request): """ Logout a user by removing all cookies that don't have the magic string 'persistent', and redirect to settings.LOGOUT_REDIRECT. """ next_param = request.GET.get('next', None) next_url = (next_param if next_param and is_safe_url(next_param) else getattr(settings, 'LOGOUT_REDIRECT', None)) response = (redirect(next_url) if next_url else render(request, 'idbase/logout.html')) logger.debug('Logging out {}@washington.edu and redirecting to {}'.format( request.uwnetid, next_url)) # delete all cookies that don't contain the string 'persistent' delete_keys = [key for key in request.COOKIES if not re.search(r'persistent', key, re.IGNORECASE)] for key in delete_keys: response.delete_cookie(key) return response
def form_valid(self, form): """ This method is executed when submitted form is valid. It redirects to ``success_url`` if no ``next`` url is provided. Otherwise it redirects to ``next`` url. :param form: ``forms.Form`` instance :return: ``HttpResponse`` instance """ redirect_to = self.request.POST.get('next', '') auth.login(self.request, form.user_cache) # check if next is a valid url if not is_safe_url(redirect_to, self.request.get_host()): return super(WebmailLoginView, self).form_valid(form) else: return redirect(redirect_to)
def get_next_url(request, redirect_field_name): """Retrieves next url from request Note: This verifies that the url is safe before returning it. If the url is not safe, this returns None. :arg HttpRequest request: the http request :arg str redirect_field_name: the name of the field holding the next url :returns: safe url or None """ next_url = request.GET.get(redirect_field_name) if next_url: kwargs = { 'url': next_url, 'host': request.get_host() } # NOTE(willkg): Django 1.11+ allows us to require https, too. if django.VERSION >= (1, 11): kwargs['require_https'] = request.is_secure() is_safe = is_safe_url(**kwargs) if is_safe: return next_url return None
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": if request.POST.has_key('login'): form = authentication_form(request, data=request.POST) if form.is_valid(): if form.get_user() and form.get_user().is_active: # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(djsettings.LOGIN_REDIRECT_URL) auth_login(request, form.get_user()) Message.objects.create(type=u'????', user=request.user, action=u'????', action_ip=UserIP(request), content='???? %s'%request.user) return HttpResponseRedirect(redirect_to) else: Message.objects.create(type=u'????', user=request.POST.get('username'), action=u'????', action_ip=UserIP(request), content=u'?????? %s'%request.POST.get('username')) else: form = authentication_form(request) return render(request, 'registration/login.html', {'form':form, 'title':'????'})
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('/')
def next_redirect(request, fallback, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a ``?next=...`` GET arg or the URL of a given view (``fallback``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = request.POST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = resolve_url(fallback) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = '&' if '?' in next else '?' next += joiner + urlencode(get_kwargs) + anchor return HttpResponseRedirect(next)
def get_redirect_url(self, *args, **kwargs): client = OAuth2Session( client_id=settings.OAUTH['client_id'], redirect_uri=settings.OAUTH['redirect_domain'] + reverse('oauth_return_view'), scope=['view_profile'], ) # extract next url next_url = self.request.GET.get('next', None) # save it to the session if next_url and is_safe_url(next_url): self.request.session['login_next_url'] = next_url # the user is then redirected to the auth provider with the right parameters url, state = client.authorization_url(settings.OAUTH['authorization_url']) # the nonce is saved inside the session self.request.session['oauth2_nonce'] = state return url
def logout(request): auth_logout(request) if 'next' in request.POST or 'next' in request.GET: next_page = request.POST.get('next', request.GET.get('next')) if not is_safe_url(url=next_page, host=request.get_host()): return HttpResponseRedirect(request.path) else: return HttpResponseRedirect(next_page) current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': 'Logged out' } return TemplateResponse(request, 'logout.html', context)
def post(self, request): form = LoginForm(request, data=request.POST) if form.is_valid(): # Determine where to direct user after successful login redirect_to = request.POST.get('next', '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = reverse('home') # Authenticate user auth_login(request, form.get_user()) messages.info(request, "Logged in as {}.".format(request.user)) return HttpResponseRedirect(redirect_to) return render(request, self.template_name, { 'form': form, })
def set_lang(request): """ django.views.i18n.set_language() with GET """ next = request.GET.get('next', request.GET.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) lang_code = request.GET.get('lang', 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
def help_view(request, page='payment-issues'): """ FAQ sections @param request: the HTTP request @param page: page slug """ context = { 'breadcrumbs_back': settings.START_PAGE_URL, } return_to = request.META.get('HTTP_REFERER') or '' return_to_within_site = is_safe_url(url=return_to, host=request.get_host()) return_to_same_page = return_to.split('?')[0] == request.build_absolute_uri().split('?')[0] if page != 'payment-issues' and return_to_within_site and not return_to_same_page: context['breadcrumbs_back'] = return_to response = render(request, 'send_money/help/%s.html' % page, context=context) return make_response_cacheable(response)
def post(self, request): form = self.form_class(data=request.POST) # NOTE: authenticate is already called internally in form.clean if form.is_valid(): username_or_email = request.POST['username'] password = request.POST['password'] # NOTE: authenticate is already called internally in form.clean so there is no need to verify the result user = authenticate(username=username_or_email, password=password) login(request, user) request.session[translation.LANGUAGE_SESSION_KEY] = user.language redirect_to = request.POST.get('next', request.GET.get('next', reverse('landing_page:home'))) redirect_to = (redirect_to if is_safe_url(redirect_to, request.get_host()) else reverse('landing_page:home')) if redirect_to == "": return HttpResponseRedirect(reverse("landing_page:home")) else: return HttpResponseRedirect(redirect_to) return render(request, 'registration/login.html', {'form': form})
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": form = authentication_form(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)
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)
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 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_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): 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
def _get_login_redirect_url(request, redirect_to): # Ensure the user-originating redirection URL is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): return resolve_url(settings.LOGIN_REDIRECT_URL) return redirect_to
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) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) 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)
def _login_redirect_url(request, fallback_to=None): redirect_to = request.POST.get('next', request.GET.get('next', '')) if not redirect_to or not is_safe_url(url=redirect_to, host=request.get_host()): return fallback_to or django_settings.LOGIN_REDIRECT_URL return redirect_to
def get_success_url(self): """Ensure the user-originating redirection URL is 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(), ) if not url_is_safe: return resolve_url(settings.LOGIN_REDIRECT_URL) return redirect_to
def get_success_url(self): redirect_to = self.request.REQUEST.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to
def _get_login_redirect_url(self, request, redirect_to): # Ensure the user-originating redirection URL is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): return resolve_url(settings.LOGIN_REDIRECT_URL) return redirect_to
def get_next_url(request, default): next_url = default if OCCURRENCE_CANCEL_REDIRECT: next_url = OCCURRENCE_CANCEL_REDIRECT _next_url = request.GET.get('next') if request.method in ['GET', 'HEAD'] else request.POST.get('next') if _next_url and is_safe_url(url=_next_url, host=request.get_host()): next_url = _next_url return next_url
def get_email_confirmation_url(self, request, emailconfirmation): url = super().get_email_confirmation_url(request, emailconfirmation) if 'next' in request.POST and is_safe_url(request.POST['next']): return '{}?next={}'.format(url, quote(request.POST['next'])) else: return url
def get_email_confirmation_redirect_url(self, request): if 'next' in request.GET and is_safe_url(request.GET['next']): return request.GET['next'] else: return super().get_email_confirmation_redirect_url(request)
def get_redirect_url(request, default=settings.LOGIN_REDIRECT_URL): """ ????????? ?????? ??? ????????? ?? POST, GET ??? settings """ redirect_to = request.POST.get( REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, '') ) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(default) return redirect_to
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 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_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): 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 # Always set cookie 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
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is None: messages.error(request, _('No user account matches the entered credentials.')) return redirect('orga:login') if not user.is_active: messages.error(request, _('User account is deactivated.')) return redirect('orga:login') login(request, user) params = request.GET.copy() url = urllib.parse.unquote(params.pop('next', [''])[0]) if url and is_safe_url(url, request.get_host()): return redirect(url + ('?' + params.urlencode() if params else '')) # check where to reasonably redirect: # orga of a running event? go to that event. # speaker of a running event? go to that event. # neither? go to (a) current cfp # no current cfp? dummy page messages.success(request, random.choice([ _('Hi, nice to see you!'), _('Welcome!'), _('I hope you are having a good day :)'), _('Remember: organizing events is lots of work, but it pays off.'), _('If you are waiting for feedback from your speakers, try sending a mail to a subset of them.'), _('Remember to provide your speakers with all information they need ahead of time.'), _('Even the busiest event organizers should make time to see at least one talk ;)'), ])) return redirect(reverse('orga:dashboard'))
def form_valid(self, form): pk = form.save() user = User.objects.get(pk=pk) login(self.request, user, backend='django.contrib.auth.backends.ModelBackend') url = self.request.GET.get('next') if url and is_safe_url(url, self.request.get_host()): return redirect(url) return redirect(reverse('cfp:event.user.submissions', kwargs={ 'event': self.request.event.slug }))
def get_redirect_url(self): 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 ''
def retrieve_next(request): next = request.COOKIES.get(REDIRECT_COOKIE_NAME) if func_supports_parameter(is_safe_url, 'allowed_hosts'): # Django 1.11 kw = {'allowed_hosts': {request.get_host()}} else: kw = {'host': request.get_host()} return next if is_safe_url(url=next, **kw) else None
def is_safe_url(url, allowed_hosts): host, = allowed_hosts return _orig_is_safe_url(url=url, host=host)
def retrieve_next(request): next = request.session.pop(REDIRECT_SESSION_KEY, None) return ( next if is_safe_url(url=next, allowed_hosts=[request.get_host()]) else None )
def form_valid(self, form): user = form.save() login(self.request, user) if not self.request.GET.get('next', False): return redirect(reverse('index')) else: if is_safe_url(self.request.GET['next']): return redirect(self.request.GET['next']) else: return redirect(reverse('index'))
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": form = authentication_form(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, 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) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)