Python django.conf.settings.LOGIN_URL Examples
The following are 30
code examples of django.conf.settings.LOGIN_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.conf.settings
, or try the search function
.
Example #1
Source File: auth.py From hummer with Apache License 2.0 | 7 votes |
def login_required(login_url=None): """ Decorator for views that checks that the user is authenticated, redirecting to login_url page if necessary. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): is_login, username, is_staff = is_authenticated(request) if is_login: kwargs['username'] = username kwargs['is_staff'] = is_staff return view_func(request, *args, **kwargs) resolved_login_url = (login_url or settings.LOGIN_URL) return HttpResponseRedirect(resolved_login_url) return _wrapped_view return decorator
Example #2
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 #3
Source File: views.py From bioforum with MIT License | 6 votes |
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirect 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(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='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # 4 views for password reset: # - password_reset sends the mail # - password_reset_done shows a success message for the above # - password_reset_confirm checks the link the user clicked and # prompts for a new password # - password_reset_complete shows a success message for the above
Example #4
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 #5
Source File: context.py From coursys with GNU General Public License v3.0 | 6 votes |
def media(request): """ Add context things that we need """ # A/B testing: half of instructors and TAs see a different search box instr_ta = is_instr_ta(request.user.username) instr_ta_ab = instr_ta and request.user.is_authenticated and request.user.id % 2 == 0 # GRAD_DATE(TIME?)_FORMAT for the grad/ra/ta apps return {'GRAD_DATE_FORMAT': settings.GRAD_DATE_FORMAT, 'GRAD_DATETIME_FORMAT': settings.GRAD_DATETIME_FORMAT, 'LOGOUT_URL': settings.LOGOUT_URL, 'LOGIN_URL': settings.LOGIN_URL, 'STATIC_URL': settings.STATIC_URL, 'is_instr_ta': instr_ta, 'instr_ta_ab': instr_ta_ab, 'request_path': request.path, 'CourSys': product_name(request), 'help_email': help_email(request), }
Example #6
Source File: views.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ 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(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='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # 4 views for password reset: # - password_reset sends the mail # - password_reset_done shows a success message for the above # - password_reset_confirm checks the link the user clicked and # prompts for a new password # - password_reset_complete shows a success message for the above
Example #7
Source File: views.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirect 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(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='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above
Example #8
Source File: views.py From bioforum with MIT License | 6 votes |
def password_reset_complete(request, template_name='registration/password_reset_complete.html', extra_context=None): warnings.warn("The password_reset_complete() view is superseded by the " "class-based PasswordResetCompleteView().", RemovedInDjango21Warning, stacklevel=2) context = { 'login_url': resolve_url(settings.LOGIN_URL), 'title': _('Password reset complete'), } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above
Example #9
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 #10
Source File: test_views.py From dirigible-spreadsheet with MIT License | 6 votes |
def test_copy_sheet_requires_login_for_anonymous_user(self): self.sheet.is_public = True worksheet = Worksheet() worksheet.a1.value = 'some-cell-content' self.sheet.jsonify_worksheet(worksheet) self.sheet.save() self.request.user = AnonymousUser() self.request.META['SERVER_NAME'] = 'servername' self.request.META['SERVER_PORT'] = '80' self.request.get_full_path = lambda: 'request-path' response = copy_sheet(self.request, self.user.username, self.sheet.id) self.assertTrue(isinstance(response, HttpResponseRedirect)) redirect_url = urlparse(response['Location']) self.assertEquals(redirect_url.path, settings.LOGIN_URL) redirect_query_params = parse_qs(redirect_url.query) self.assertEquals(redirect_query_params['next'], ['request-path'])
Example #11
Source File: views.py From openhgsenti with Apache License 2.0 | 6 votes |
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ 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(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='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # 4 views for password reset: # - password_reset sends the mail # - password_reset_done shows a success message for the above # - password_reset_confirm checks the link the user clicked and # prompts for a new password # - password_reset_complete shows a success message for the above
Example #12
Source File: views.py From hoover-search with MIT License | 6 votes |
def whoami(request): if settings.HOOVER_AUTHPROXY: logout_url = '/__auth/logout' else: logout_url = reverse('logout') + '?next=/' urls = { 'login': settings.LOGIN_URL, 'admin': reverse('admin:index'), 'logout': logout_url, 'hypothesis_embed': settings.HOOVER_HYPOTHESIS_EMBED, } try: password_change = reverse('password_change') except NoReverseMatch: pass else: urls['password_change'] = password_change return JsonResponse({ 'username': request.user.username, 'admin': request.user.is_superuser, 'urls': urls, 'title': settings.HOOVER_TITLE, })
Example #13
Source File: middleware.py From hoover-search with MIT License | 6 votes |
def process_request(self, request): WHITELIST = [ r'^/accounts/', r'^/invitation/', r'^/static/', r'^/_ping$', r'^/_is_staff$', ] for pattern in WHITELIST: if re.match(pattern, request.path): return user = request.user if user.is_verified(): return resolved_login_url = resolve_url(settings.LOGIN_URL) return redirect_to_login(request.path, resolved_login_url, 'next')
Example #14
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 #15
Source File: __init__.py From edx-analytics-dashboard with GNU Affero General Public License v3.0 | 6 votes |
def test_authentication(self, course_id): """ Users must be logged in to view the page. """ if self.api_method: with patch(self.api_method, return_value=self.get_mock_data(course_id)): # Authenticated users should go to the course page self.login() response = self.client.get(self.path(course_id=course_id), follow=self.follow) self.assertEqual(response.status_code, self.success_status) # Unauthenticated users should be redirected to the login page self.client.logout() response = self.client.get(self.path(course_id=course_id)) self.assertRedirectsNoFollow(response, settings.LOGIN_URL, next=self.path(course_id=course_id))
Example #16
Source File: tests_middleware.py From Spirit with MIT License | 6 votes |
def test_restrict_apps(self): """ Should restrict the URLs """ url_names = [ 'spirit:topic:index-active', 'spirit:topic:private:index', 'spirit:category:index'] for url_name in url_names: url = reverse(url_name) req = RequestFactory().get(url) req.user = AnonymousUser() resp = middleware.PrivateForumMiddleware().process_request(req) self.assertIsInstance(resp, HttpResponseRedirect) self.assertEqual( resp['Location'], reverse(settings.LOGIN_URL) + '?next=' + url)
Example #17
Source File: views.py From python2017 with MIT License | 6 votes |
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ 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(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='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # 4 views for password reset: # - password_reset sends the mail # - password_reset_done shows a success message for the above # - password_reset_confirm checks the link the user clicked and # prompts for a new password # - password_reset_complete shows a success message for the above
Example #18
Source File: views.py From python2017 with MIT License | 6 votes |
def password_reset_complete(request, template_name='registration/password_reset_complete.html', extra_context=None): warnings.warn("The password_reset_complete() view is superseded by the " "class-based PasswordResetCompleteView().", RemovedInDjango21Warning, stacklevel=2) context = { 'login_url': resolve_url(settings.LOGIN_URL), 'title': _('Password reset complete'), } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above
Example #19
Source File: views.py From product-database with MIT License | 6 votes |
def browse_vendor_products(request): """Browse vendor specific products in the database :param request: :return: """ if login_required_if_login_only_mode(request): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) context = { "vendors": Vendor.objects.all() } selected_vendor = 1 # use ID 1 by default if request.method == "POST": vendor_id_str = [str(e) for e in context["vendors"].values_list("id", flat=True)] if request.POST['vendor_selection'] in vendor_id_str: selected_vendor = request.POST['vendor_selection'] else: if request.user.is_authenticated: selected_vendor = request.user.profile.preferred_vendor.id context['vendor_selection'] = selected_vendor return render(request, "productdb/browse/view_products_by_vendor.html", context=context)
Example #20
Source File: views.py From alfred-gmail with MIT License | 5 votes |
def oauth2_authorize(request): """ View to start the OAuth2 Authorization flow. This view starts the OAuth2 authorization flow. If scopes is passed in as a GET URL parameter, it will authorize those scopes, otherwise the default scopes specified in settings. The return_url can also be specified as a GET parameter, otherwise the referer header will be checked, and if that isn't found it will return to the root path. Args: request: The Django request object. Returns: A redirect to Google OAuth2 Authorization. """ return_url = request.GET.get('return_url', None) # Model storage (but not session storage) requires a logged in user if django_util.oauth2_settings.storage_model: if not request.user.is_authenticated(): return redirect('{0}?next={1}'.format( settings.LOGIN_URL, parse.quote(request.get_full_path()))) # This checks for the case where we ended up here because of a logged # out user but we had credentials for it in the first place elif get_storage(request).get() is not None: return redirect(return_url) scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes) if not return_url: return_url = request.META.get('HTTP_REFERER', '/') flow = _make_flow(request=request, scopes=scopes, return_url=return_url) auth_url = flow.step1_get_authorize_url() return shortcuts.redirect(auth_url)
Example #21
Source File: decorators.py From openhgsenti with Apache License 2.0 | 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: test_views.py From boss-oidc with Apache License 2.0 | 5 votes |
def _configure_settings(self): # Setup the configuration as described in the documentation bossoidc.settings.configure_oidc('https://auth', 'client_id', 'https://localhost') # Copy the values into the active settings settings.LOGIN_URL = bossoidc.settings.LOGIN_URL settings.LOGOUT_URL = bossoidc.settings.LOGOUT_URL settings.OIDC_PROVIDERS = bossoidc.settings.OIDC_PROVIDERS settings.OIDC_AUTH = bossoidc.settings.OIDC_AUTH
Example #23
Source File: test_mixins.py From Simple-Q-A-App-using-Python-Django with MIT License | 5 votes |
def test_login_required_redirects(self): """ Anonymous users should be redirected to the LOGIN_URL """ request = self.factory.get('some-random-place') request.user = AnonymousUser() response = SomeView.as_view()(request) self.assertEqual(response.status_code, 302) self.assertTrue(settings.LOGIN_URL in response.url)
Example #24
Source File: mixins.py From openhgsenti with Apache License 2.0 | 5 votes |
def get_login_url(self): """ Override this method to override the login_url attribute. """ login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( '{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override ' '{0}.get_login_url().'.format(self.__class__.__name__) ) return force_text(login_url)
Example #25
Source File: mixins.py From troupon with MIT License | 5 votes |
def dispatch(self, request, *args, **kwargs): if not request.user.profile.is_approved_merchant(): messages.error( request, 'You do not have the permission required to perform the ' 'requested operation.') if not request.user: return redirect(settings.LOGIN_URL) else: return redirect(reverse('account_merchant_register')) return super(MerchantMixin, self).dispatch(request, *args, **kwargs)
Example #26
Source File: decorators.py From GTDWeb with GNU General Public License v2.0 | 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 #27
Source File: middleware.py From hoover-search with MIT License | 5 votes |
def process_request(self, request): if not settings.HOOVER_TWOFACTOR_AUTOLOGOUT: return user = request.user if user.is_authenticated: login_time = request.session.get(LOGIN_TIME_SESSION_KEY) or 0 if time() - login_time > settings.HOOVER_TWOFACTOR_AUTOLOGOUT: signals.auto_logout.send(AutoLogout, username=user.get_username()) logout(request) login = "{}?next={}".format(settings.LOGIN_URL, request.path) return HttpResponseRedirect(login)
Example #28
Source File: test_views.py From django-mptt-comments with MIT License | 5 votes |
def test_authenticated_user_post_comment(self): self.client.login(username='test', password='test') response = self.client.post(reverse('mptt-comments-post-comment'), data={}) self.assertEqual(response.status_code, 400) # TODO: override_settings doesn't work as control is module level. # see: https://docs.djangoproject.com/en/2.1/topics/testing/tools/#overriding-settings # @override_settings(MPTT_COMMENTS_ALLOW_ANONYMOUS=False) # def test_doesnt_allow_anonymous_user_post_comment(self): # response = self.client.post(reverse('django_mptt_comments:mptt-comments-post-comment'), data={}) # self.assertEqual(response.status_code, 302) # self.assertEqual(response.url, settings.LOGIN_URL + '?next=/post/')
Example #29
Source File: test_views.py From edx-analytics-dashboard with GNU Affero General Public License v3.0 | 5 votes |
def test_login_redirect(self): """ The login page should redirect users to the OAuth2 provider's login page. """ response = self.client.get(settings.LOGIN_URL) path = reverse('social:begin', args=['edx-oauth2']) self.assertRedirectsNoFollow(response, path, status_code=302)
Example #30
Source File: auth.py From coursys with GNU General Public License v3.0 | 5 votes |
def login_redirect(next_url): """ Send the user to log in, and then to next_url """ return HttpResponseRedirect(settings.LOGIN_URL + '?' + urlencode({'next': next_url}))