Python django.contrib.auth.REDIRECT_FIELD_NAME Examples
The following are 30
code examples of django.contrib.auth.REDIRECT_FIELD_NAME().
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.contrib.auth
, 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: decorator.py From zulip with Apache License 2.0 | 7 votes |
def zulip_login_required( function: Optional[ViewFuncT]=None, redirect_field_name: str=REDIRECT_FIELD_NAME, login_url: str=settings.HOME_NOT_LOGGED_IN, ) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]: actual_decorator = lambda function: user_passes_test( logged_in_and_active, login_url=login_url, redirect_field_name=redirect_field_name, )( zulip_otp_required( redirect_field_name=redirect_field_name, login_url=login_url, )(add_logging_data(function)) ) if function: return actual_decorator(function) return actual_decorator # nocoverage # We don't use this without a function
Example #3
Source File: decorator.py From zulip with Apache License 2.0 | 7 votes |
def user_passes_test(test_func: Callable[[HttpResponse], bool], login_url: Optional[str]=None, redirect_field_name: str=REDIRECT_FIELD_NAME) -> Callable[[ViewFuncT], ViewFuncT]: """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse: if test_func(request): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urllib.parse.urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urllib.parse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login( path, resolved_login_url, redirect_field_name) return cast(ViewFuncT, _wrapped_view) # https://github.com/python/mypy/issues/1927 return decorator
Example #4
Source File: middleware.py From esproxy with MIT License | 6 votes |
def process_view(self, request, view_func, view_args, view_kwargs): """ Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(request, *view_args, **view_kwargs) if view_func == logout: return cas_logout(request, *view_args, **view_kwargs) # The rest of this method amends the Django admin authorization wich # will post a username/password dialog to authenticate to django admin. if not view_func.__module__.startswith('django.contrib.admin.'): return None if request.user.is_authenticated(): if request.user.is_staff: return None else: raise PermissionDenied("No staff priviliges") params = urlencode({auth.REDIRECT_FIELD_NAME: request.get_full_path()}) return HttpResponseRedirect(settings.LOGIN_URL + '?' + params)
Example #5
Source File: view_mixins.py From TWLight with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): if not self.test_func_tou_required(request.user): messages.add_message( request, messages.INFO, "You need to agree to the terms of use before you can do that.", ) # Remember where they were trying to go, so we can redirect them # back after they agree. There's logic in TermsView to pick up on # this parameter. next_path = request.path next_param = urlencode({REDIRECT_FIELD_NAME: next_path}) path = reverse_lazy("terms") new_url = ParseResult( scheme="", netloc="", path=str(path), params="", query=str(next_param), fragment="", ).geturl() return HttpResponseRedirect(new_url) return super(ToURequired, self).dispatch(request, *args, **kwargs)
Example #6
Source File: decorators.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def is_owner(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # assume username is first arg if request.user.is_authenticated(): if request.user.username == kwargs['username']: return view_func(request, *args, **kwargs) protocol = "https" if request.is_secure() else "http" return HttpResponseRedirect("%s://%s" % (protocol, request.get_host())) path = request.build_absolute_uri() login_url = request.build_absolute_uri(settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse.urlparse(login_url)[:2] current_scheme, current_netloc = urlparse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login(path, None, REDIRECT_FIELD_NAME) return _wrapped_view
Example #7
Source File: decorators.py From django-uniauth with GNU Lesser General Public License v3.0 | 6 votes |
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Replacement for django's built-in login_required decorator that also requires user to not be a temporary user (must have completed signup process). It can be used identically to the built-in version. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated and not is_tmp_user(u), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
Example #8
Source File: utils.py From django-uniauth with GNU Lesser General Public License v3.0 | 6 votes |
def get_redirect_url(request, use_referer=False, default_url=None): """ Returns the URL to redirect to once business at the current URL is completed. Picks the first usable URL from the following list: 1. URL provided as GET parameter under REDIRECT_FIELD_NAME 2. Referring page if use_referer is True, and set in header 3. default_url parameter 4. UNIAUTH_LOGIN_REDIRECT_URL setting """ redirect_url = request.GET.get(REDIRECT_FIELD_NAME) if not redirect_url: if use_referer: redirect_url = request.META.get('HTTP_REFERER') if not redirect_url: redirect_url = resolve_url(default_url or get_setting('UNIAUTH_LOGIN_REDIRECT_URL')) prefix = urlunparse( (get_protocol(request), request.get_host(), '', '', '', ''), ) if redirect_url.startswith(prefix): redirect_url = redirect_url[len(prefix):] return redirect_url
Example #9
Source File: utils.py From django-uniauth with GNU Lesser General Public License v3.0 | 6 votes |
def get_service_url(request, redirect_url=None): """ Returns the service URL to provide to the CAS server for the provided request. Accepts an optional redirect_url, which defaults to the value of get_redirect_url(request). """ service_url = urlunparse( (get_protocol(request), request.get_host(), request.path, '', '', ''), ) query_params = request.GET.copy() query_params[REDIRECT_FIELD_NAME] = redirect_url or \ get_redirect_url(request) # The CAS server may have added the ticket as an extra query # parameter upon checking the credentials - ensure it is ignored query_params.pop('ticket', None) service_url += '?' + urlencode(query_params) return service_url
Example #10
Source File: decorators.py From tethys with BSD 2-Clause "Simplified" License | 6 votes |
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for Tethys App controllers that checks whether a user has a permission. """ def decorator(controller_func): def wrapper(request, *args, **kwargs): if not getattr(settings, 'ENABLE_OPEN_PORTAL', False): from django.contrib.auth.decorators import login_required as lr dec = lr(function=function, redirect_field_name=redirect_field_name, login_url=login_url) controller = dec(controller_func) return controller(request, *args, **kwargs) else: return controller_func(request, *args, **kwargs) return wraps(controller_func)(wrapper) return decorator
Example #11
Source File: view_mixins.py From TWLight with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): if not self.test_func_email_required(request.user): messages.add_message( request, messages.INFO, "You need to have an email address on file before you can do that.", ) # Remember where they were trying to go, so we can redirect them # back after they agree. There's logic in TermsView to pick up on # this parameter. next_path = request.path next_param = urlencode({REDIRECT_FIELD_NAME: next_path}) path = reverse_lazy("users:email_change") new_url = ParseResult( scheme="", netloc="", path=str(path), params="", query=str(next_param), fragment="", ).geturl() return HttpResponseRedirect(new_url) return super(EmailRequired, self).dispatch(request, *args, **kwargs)
Example #12
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 #13
Source File: decorators.py From fermentrack with MIT License | 6 votes |
def gravity_support_enabled(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ def check_gravity_support_enabled(): return config.GRAVITY_SUPPORT_ENABLED actual_decorator = constance_check( check_gravity_support_enabled, next_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
Example #14
Source File: index.py From zing with GNU General Public License v3.0 | 6 votes |
def view(request): if not request.user.is_authenticated: ctx = { "next": request.GET.get(REDIRECT_FIELD_NAME, ""), } return render(request, "welcome.html", ctx) lang = request.COOKIES.get(COOKIE_NAME, None) if lang is None: supported = Language.live.cached_dict(show_all=request.user.is_superuser) lang = get_lang_from_http_header(request, supported) if lang is not None and lang not in ("projects", ""): url = reverse("pootle-language-browse", args=[lang]) else: url = reverse("pootle-projects-browse") # Preserve query strings args = request.GET.urlencode() qs = "?%s" % args if args else "" redirect_url = "%s%s" % (url, qs) return redirect(redirect_url)
Example #15
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 #16
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 #17
Source File: decorators.py From GetTogether with BSD 2-Clause "Simplified" License | 6 votes |
def setup_wanted(view_func, setup_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user has completed the setup process, redirecting to settings.SETUP_URL if required """ @wraps(view_func) def wrap(request, *args, **kwargs): if ( not request.user.is_authenticated or request.user.account.has_completed_setup ): return view_func(request, *args, **kwargs) else: resolved_setup_url = resolve_url(setup_url or settings.SETUP_URL) path = request.get_full_path() return redirect_to_login(path, resolved_setup_url, redirect_field_name) return wrap
Example #18
Source File: views.py From esproxy with MIT License | 6 votes |
def _service_url(request, redirect_to): """ Returns application service URL for CAS. """ service = _service(request) + request.path params = {} if settings.CAS_GATEWAY: params.update({settings.CAS_GATEWAY_PARAM: '1'}) if redirect_to: params.update({auth.REDIRECT_FIELD_NAME: redirect_to}) if not params: return service else: return ''.join([service, '?' if not '?' in service else '&', urlencode(params)])
Example #19
Source File: decorators.py From fermentrack with MIT License | 6 votes |
def site_is_configured(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ def check_constance_is_configured(): return config.USER_HAS_COMPLETED_CONFIGURATION actual_decorator = constance_check( check_constance_is_configured, next_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
Example #20
Source File: decorator.py From zulip with Apache License 2.0 | 6 votes |
def redirect_to_login(next: str, login_url: Optional[str]=None, redirect_field_name: str=REDIRECT_FIELD_NAME) -> HttpResponseRedirect: """ Redirects the user to the login page, passing the given 'next' page """ resolved_url = resolve_url(login_url or settings.LOGIN_URL) login_url_parts = list(urllib.parse.urlparse(resolved_url)) if redirect_field_name: querystring = QueryDict(login_url_parts[4], mutable=True) querystring[redirect_field_name] = next # Don't add ?next=/, to keep our URLs clean if next != '/': login_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urllib.parse.urlunparse(login_url_parts)) # From Django 1.8
Example #21
Source File: decorators.py From python2017 with MIT License | 5 votes |
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator
Example #22
Source File: views.py From esproxy with MIT License | 5 votes |
def _redirect_url(request): """ Redirects to referring page, or CAS_REDIRECT_URL if no referrer. """ if request.GET.get(auth.REDIRECT_FIELD_NAME): return _fix_encoding(request.GET.get(auth.REDIRECT_FIELD_NAME)) if settings.CAS_IGNORE_REFERER: return settings.CAS_REDIRECT_URL return _fix_encoding(request.META.get('HTTP_REFERER', settings.CAS_REDIRECT_URL))
Example #23
Source File: __init__.py From django-is-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirects the user to the login page, passing the given 'next' page """ resolved_url = reverse('IS:login') login_url_parts = list(urlparse(resolved_url)) if redirect_field_name: querystring = QueryDict(login_url_parts[4], mutable=True) querystring[redirect_field_name] = next login_url_parts[4] = querystring.urlencode(safe='/') raise HTTPRedirectResponseException(urlunparse(login_url_parts))
Example #24
Source File: middleware.py From django-mfa with MIT License | 5 votes |
def process_request(self, request): if request.user.is_authenticated and ((not verify_rmb_cookie(request) and is_mfa_enabled(request.user)) or (is_u2f_enabled(request.user))): if not request.session.get('verfied_otp') and not request.session.get('verfied_u2f'): current_path = request.path paths = [reverse("mfa:verify_second_factor"), reverse( "mfa:verify_second_factor_u2f"), reverse("mfa:verify_second_factor_totp")] if current_path not in paths: path = request.get_full_path() resolved_login_url = resolve_url( reverse("mfa:verify_second_factor")) from django.contrib.auth.views import redirect_to_login return redirect_to_login(path, resolved_login_url, redirect_field_name) return None
Example #25
Source File: decorators.py From python2017 with MIT License | 5 votes |
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
Example #26
Source File: admin.py From texta with GNU General Public License v3.0 | 5 votes |
def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ if request.method == 'GET' and self.has_permission(request): # Already logged-in, redirect to admin index index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(URL_PREFIX_RESOURCE+index_path) # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level, # and django.contrib.admin.forms eventually imports User. from django.contrib.admin.forms import AdminAuthenticationForm context = dict(self.each_context(request), title= ('Log in'), app_path=request.get_full_path(), ) if REDIRECT_FIELD_NAME not in request.GET and REDIRECT_FIELD_NAME not in request.POST: context[REDIRECT_FIELD_NAME] = request.get_full_path() context.update(extra_context or {}) defaults = { 'extra_context': context, 'current_app': self.name, 'authentication_form': self.login_form or AdminAuthenticationForm, 'template_name': self.login_template or 'admin/login.html', } return login(request, **defaults)
Example #27
Source File: views.py From django-u2f with BSD 2-Clause "Simplified" License | 5 votes |
def get_context_data(self, **kwargs): kwargs = super(U2FLoginView, self).get_context_data(**kwargs) kwargs[auth.REDIRECT_FIELD_NAME] = self.request.GET.get(auth.REDIRECT_FIELD_NAME, '') kwargs.update(self.kwargs.get('extra_context', {})) return kwargs
Example #28
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 #29
Source File: config.py From django-auth-adfs with BSD 2-Clause "Simplified" License | 5 votes |
def build_authorization_endpoint(self, request, disable_sso=None): """ This function returns the ADFS authorization URL. Args: request(django.http.request.HttpRequest): A django Request object disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt. Returns: str: The redirect URI """ self.load_config() redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None) if not redirect_to: redirect_to = django_settings.LOGIN_REDIRECT_URL redirect_to = base64.urlsafe_b64encode(redirect_to.encode()).decode() query = QueryDict(mutable=True) query.update({ "response_type": "code", "client_id": settings.CLIENT_ID, "resource": settings.RELYING_PARTY_ID, "redirect_uri": self.redirect_uri(request), "state": redirect_to, }) if self._mode == "openid_connect": query["scope"] = "openid" if (disable_sso is None and settings.DISABLE_SSO) or disable_sso is True: query["prompt"] = "login" return "{0}?{1}".format(self.authorization_endpoint, query.urlencode())
Example #30
Source File: admin.py From django-u2f with BSD 2-Clause "Simplified" License | 5 votes |
def make_login_view(view_class): def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ if request.method == 'GET' and self.has_permission(request): # Already logged-in, redirect to admin index index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level, # and django.contrib.admin.forms eventually imports User. from django.contrib.admin.forms import AdminAuthenticationForm context = dict( self.each_context(request), title=_('Log in'), app_path=request.get_full_path(), username=request.user.get_username(), ) if (REDIRECT_FIELD_NAME not in request.GET and REDIRECT_FIELD_NAME not in request.POST): context[REDIRECT_FIELD_NAME] = reverse('admin:index', current_app=self.name) context.update(extra_context or {}) defaults = { 'extra_context': context, 'authentication_form': self.login_form or AdminAuthenticationForm, 'template_name': self.login_template or 'admin/login.html', } request.current_app = self.name return view_class.as_view(**defaults)(request) return login