Python django.conf.settings.LOGIN_URL Examples

The following are 30 code examples for showing how to use django.conf.settings.LOGIN_URL(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: zulip   Author: zulip   File: decorator.py    License: Apache License 2.0 7 votes vote down vote up
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 2
Project: hummer   Author: wangtaoking1   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: coursys   Author: sfu-fas   File: context.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 4
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 5
Project: kobo-predict   Author: awemulya   File: decorators.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 6
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
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 7
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
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 8
Project: zulip   Author: zulip   File: decorator.py    License: Apache License 2.0 6 votes vote down vote up
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 9
Project: dirigible-spreadsheet   Author: pythonanywhere   File: test_views.py    License: MIT License 6 votes vote down vote up
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 10
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 6 votes vote down vote up
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 11
Project: Spirit   Author: nitely   File: tests_middleware.py    License: MIT License 6 votes vote down vote up
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 12
Project: openhgsenti   Author: drexly   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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 13
Project: hoover-search   Author: liquidinvestigations   File: views.py    License: MIT License 6 votes vote down vote up
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 14
Project: hoover-search   Author: liquidinvestigations   File: middleware.py    License: MIT License 6 votes vote down vote up
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 15
Project: esproxy   Author: childe   File: middleware.py    License: MIT License 6 votes vote down vote up
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 16
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 17
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
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
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
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
Project: product-database   Author: hoelsner   File: views.py    License: MIT License 6 votes vote down vote up
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
Project: Servo   Author: fpsw   File: middleware.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'user'), "The Login Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL) 
Example 21
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _forbidden_response(request, visible_to):
    """
    A nicer forbidden message that says why, and gently suggests that anonymous users log in.
    """
    error = 'Not allowed to view this page. It is visible only to %s in this course.' % (visible_to,)
    errormsg_template = '<strong>You are not currently logged in</strong>. You may be able to view this page if you <a href="%s">log in</a>'
    errormsg = None
    if not request.user.is_authenticated:
        url = conditional_escape(settings.LOGIN_URL + '?next=' + request.get_full_path())
        errormsg = mark_safe(errormsg_template % (url))

    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg) 
Example 22
Project: coursys   Author: sfu-fas   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def user_passes_test(test_func, login_url=None,
                     redirect_field_name=REDIRECT_FIELD_NAME, force_privacy=False):
    """Replacement for django.contrib.auth.decorators.user_passes_test that
    returns 403 Forbidden if the user is already logged in.
    """

    if not login_url:
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if test_func(request, **kwargs):
                if needs_privacy_signature(request, only_relevant_roles=not force_privacy):
                    # logic there: usually only check for the admin roles we know have a privacy implication. If we're
                    # passed force_privacy, then views must have the privacy agreement.
                    return privacy_redirect(request)
                elif needs_privacy_signature_da(request):
                    return privacy_da_redirect(request)
                else:
                    return view_func(request, *args, **kwargs)
            elif request.user.is_authenticated:
                return ForbiddenResponse(request)
            else:
                path = '%s?%s=%s' % (login_url, redirect_field_name,
                                     urlquote(request.get_full_path()))
                return HttpResponseRedirect(path)
        return wrapper
    return decorator 
Example 23
Project: coursys   Author: sfu-fas   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ForbiddenResponse(request, errormsg=None, exception=None):
    error = mark_safe("You do not have permission to access this resource.")
    if not request.user.is_authenticated:
        login_url = settings.LOGIN_URL + '?' + urllib.parse.urlencode({'next': request.get_full_path()})
        error += mark_safe(' You are <strong>not logged in</strong>, so maybe <a href="%s">logging in</a> would help.' % (login_url))
    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg) 
Example 24
Project: coursys   Author: sfu-fas   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
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})) 
Example 25
Project: django-mptt-comments   Author: zmrenwu   File: test_views.py    License: MIT License 5 votes vote down vote up
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 26
Project: GTDWeb   Author: lanbing510   File: decorators.py    License: GNU General Public License v2.0 5 votes vote down vote up
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
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def logout_then_login(request, login_url=None, current_app=None, extra_context=None):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return logout(request, login_url, current_app=current_app, extra_context=extra_context) 
Example 28
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            current_app=None, extra_context=None):
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    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) 
Example 29
Project: Tenma   Author: Tenma-Server   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'user'), "The Login Required middleware requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL + "?next=" + request.path) 
Example 30
Project: peering-manager   Author: respawner   File: middleware.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, request):
        if settings.LOGIN_REQUIRED and not request.user.is_authenticated:
            if (
                not request.path_info.startswith(reverse("api-root"))
                and request.path_info != settings.LOGIN_URL
            ):
                return HttpResponseRedirect(
                    "{}?next={}".format(settings.LOGIN_URL, request.path_info)
                )

        return self.get_response(request)