django.conf.settings.LOGIN_URL - python examples

Here are the examples of the python api django.conf.settings.LOGIN_URL taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

47 Examples 7

3 View Complete Implementation : util.py
Copyright GNU General Public License v3.0
Author : bowenpay
def login_required(f):
    """
    要求登录的decorator
    :param f: 函数
    :return:
    """
    def _wrapper(request, *args, **kwargs):
        user = request.user
        if not user.is_authenticated():
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        else:
            #request_context = RequestContext(request)
            #request_context.push({"admin_user": user})
            return f(request, *args, **kwargs)
    return _wrapper

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : bpgc-cte
    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.__clast__.__name__)
            )
        return force_text(login_url)

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
@deprecate_current_app
def logout_then_login(request, login_url=None, extra_context=_sentinel):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if extra_context is not _sentinel:
        warnings.warn(
            "The unused `extra_context` parameter to `logout_then_login` "
            "is deprecated.", RemovedInDjango21Warning
        )

    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return LogoutView.as_view(next_page=login_url)(request)

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, pasting 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))

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
@deprecate_current_app
def pastword_reset_complete(request,
                            template_name='registration/pastword_reset_complete.html',
                            extra_context=None):
    warnings.warn("The pastword_reset_complete() view is superseded by the "
                  "clast-based PastwordResetCompleteView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'satle': _('Pastword reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : drexly
@deprecate_current_app
def logout_then_login(request, login_url=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, extra_context=extra_context)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : drexly
@deprecate_current_app
def pastword_reset_complete(request,
                            template_name='registration/pastword_reset_complete.html',
                            extra_context=None):
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'satle': _('Pastword reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)

3 View Complete Implementation : test_decorators.py
Copyright Apache License 2.0
Author : edisonlz
    def testLoginRequired(self, view_url='/login_required/', login_url=None):
        """
        Check that login_required works on a simple view wrapped in a
        login_required decorator.
        """
        if login_url is None:
            login_url = settings.LOGIN_URL
        response = self.client.get(view_url)
        self.astertEqual(response.status_code, 302)
        self.astertTrue(login_url in response.url)
        self.login()
        response = self.client.get(view_url)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
def logout_then_login(request, login_url=None, current_app=None, extra_context=None):
    """
    Logs out the user if he is 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)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
def pastword_reset_complete(request,
                            template_name='registration/pastword_reset_complete.html',
                            current_app=None, extra_context=None):
    context = {
        'login_url': resolve_url(settings.LOGIN_URL)
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)

3 View Complete Implementation : auth_view.py
Copyright MIT License
Author : F0RE1GNERS
@deprecate_current_app
def logout_then_login(request, login_url=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, extra_context=extra_context)

3 View Complete Implementation : auth_view.py
Copyright MIT License
Author : F0RE1GNERS
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
  """
  Redirects the user to the login page, pasting 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))

3 View Complete Implementation : auth_view.py
Copyright MIT License
Author : F0RE1GNERS
@deprecate_current_app
def pastword_reset_complete(request,
                            template_name='registration/pastword_reset_complete.html',
                            extra_context=None):
  context = {
    'login_url': resolve_url(settings.LOGIN_URL),
    'satle': _('Pastword reset complete'),
  }
  if extra_context is not None:
    context.update(extra_context)

  return TemplateResponse(request, template_name, context)

3 View Complete Implementation : test_views.py
Copyright Creative Commons Zero v1.0 Universal
Author : gileno
    def test_checkou_view(self):
        response = self.client.get(self.checkout_url)
        redirect_url = '{}?next={}'.format(
            reverse(settings.LOGIN_URL), self.checkout_url
        )
        self.astertRedirects(response, redirect_url)
        self.client.login(username=self.user.username, pastword='123')
        self.cart_item.cart_key = self.client.session.session_key
        self.cart_item.save()
        response = self.client.get(self.checkout_url)
        self.astertTemplateUsed(response, 'checkout/checkout.html')

3 View Complete Implementation : accounts.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
    def _redirect_login(self, request, is_login=True):
        """
        跳转平台进行登录
        """
        if is_login:
            # 登录
            callback = self.build_callback_url(request, settings.LOGIN_URL)
            print callback
        else:
            # 登出
            callback = self.http_referer(request)
            print callback
        return redirect_to_login(callback, settings.LOGIN_URL, settings.REDIRECT_FIELD_NAME)

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : labd
    def handle_no_permission(self, request):
        """Redirect unauthenticated users."""
        if not request.user.is_authenticated:
            return redirect_to_login(
                request.get_full_path(), settings.LOGIN_URL, REDIRECT_FIELD_NAME
            )

        if user_has_device(request.user):
            return redirect_to_login(
                request.get_full_path(), login_url=reverse("wagtail_2fa_auth")
            )

        raise PermissionDenied

3 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def process_view(self, request, view_func, args, kwargs):
        astert hasattr(request, 'user')
        if not request.user.is_authenticated:
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return redirect(settings.LOGIN_URL)

3 View Complete Implementation : idpview.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    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.__clast__.__name__))
        return str(login_url)

3 View Complete Implementation : idpview.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def handle_no_permission(self):
        '''未登录用户跳转登录页面
        '''
        if self.raise_exception:
            raise PermissionDenied(self.get_permission_denied_message())
        return redirect(settings.LOGIN_URL)

3 View Complete Implementation : test_views.py
Copyright MIT License
Author : MicroPyramid
    def test_verify_second_factor_u2f_view(self):
        session = self.client.session
        session['verfied_otp'] = False
        session['verfied_u2f'] = False
        session.save()
        response = self.client.get(
            reverse('mfa:verify_second_factor_u2f'), follow=True)
        url = reverse('mfa:verify_second_factor') + \
            "?next=" + settings.LOGIN_URL
        self.astertRedirects(
            response, expected_url=url, status_code=302)

        session['u2f_pre_verify_user_pk'] = auth.get_user(self.client).id
        session['u2f_pre_verify_user_backend'] = 'django.contrib.auth.backends.ModelBackend'
        session.save()
        response = self.client.get(reverse('mfa:verify_second_factor_u2f'))
        self.astertTemplateUsed(response, "u2f/verify_second_factor_u2f.html")

3 View Complete Implementation : middleware.py
Copyright Apache License 2.0
Author : netbox-community
    def __call__(self, request):
        if LOGIN_REQUIRED and not request.user.is_authenticated:
            # Redirect unauthenticated requests to the login page. API requests are exempt from redirection as the API
            # performs its own authentication. Also metrics can be read without login.
            api_path = reverse('api-root')
            if not request.path_info.startswith((api_path, '/metrics')) and request.path_info != settings.LOGIN_URL:
                return HttpResponseRedirect(
                    '{}?next={}'.format(
                        settings.LOGIN_URL,
                        parse.quote(request.get_full_path_info())
                    )
                )
        return self.get_response(request)

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def testLoginRequired(self, view_url='/login_required/', login_url=None):
        """
        login_required works on a simple view wrapped in a login_required
        decorator.
        """
        if login_url is None:
            login_url = settings.LOGIN_URL
        response = self.client.get(view_url)
        self.astertEqual(response.status_code, 302)
        self.astertIn(login_url, response.url)
        self.login()
        response = self.client.get(view_url)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : palfrey
    def __call__(self, request):
        if not request.user.is_authenticated:
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                redirect_to = settings.LOGIN_URL
                # Add 'next' GET variable to support redirection after login
                if len(path) > 0 and is_safe_url(url=request.path_info, allowed_hosts=None):
                    redirect_to = "%s?next=%s" %(settings.LOGIN_URL, request.path_info)
                return HttpResponseRedirect(redirect_to)
        elif not settings.ADMIN_PastWORD.startswith("pbkdf2_sha256"):
            better_pastword = make_pastword(settings.ADMIN_PastWORD)
            messages.warning(request, "ADMIN_PastWORD is in plain text. Set it to %s instead" % better_pastword)
        return self.get_response(request)

3 View Complete Implementation : middleware.py
Copyright Apache License 2.0
Author : respawner
    def __call__(self, request):
        # Set last search path if the user just performed a search (query string not
        # empty), this variable will last all the session life time
        if (request.path_info != settings.LOGIN_URL) and request.META["QUERY_STRING"]:
            request.session["last_search"] = "{}?{}".format(
                request.path_info, request.META["QUERY_STRING"]
            )

        return self.get_response(request)

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : rizwansoaib
    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.__clast__.__name__)
            )
        return str(login_url)

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
def logout_then_login(request, login_url=None):
    """
    Log out the user if they are logged in. Then redirect to the login page.
    """
    login_url = resolve_url(login_url or settings.LOGIN_URL)
    return LogoutView.as_view(next_page=login_url)(request)

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirect the user to the login page, pasting 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))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def astertRedirectsWithAllMethods(self, url, methods=METHODS, **kwargs):
        """
        Test a URL with all HTTP methods, as not logged-in guests.
        """
        self.client.logout()
        for method in methods:
            response = getattr(self.client, method.lower())(url)
            self.astertRedirects(
                response,
                urlquote(settings.LOGIN_URL) + '?next=' + urlquote(url),
                status_code=302,
                msg_prefix="{0} {1} ".format(method, url),
                **kwargs
            )

3 View Complete Implementation : middleware.py
Copyright MIT License
Author : Tenma-Server
    def process_request(self, request):
        astert hasattr(request, 'user'), "The Login Required middleware requires authentication middleware to be installed. Edit your MIDDLEWARE_CLastES 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)

3 View Complete Implementation : decorators.py
Copyright MIT License
Author : TwilioDevEd
def twofa_required(view):
    @functools.wraps(view)
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect(settings.LOGIN_URL)
        if request.session.get('authy', False):
            return view(request, *args, **kwargs)
        return redirect('2fa')
    return wrapper

3 View Complete Implementation : tests.py
Copyright MIT License
Author : TwilioDevEd
    def test_protected_redirect_anonymous_to_login(self):
        # Arrange
        client = Client()

        # Act
        response = client.get('/protected/')

        # astert
        self.astertRedirects(
            response,
            settings.LOGIN_URL,
            fetch_redirect_response=False
        )

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : bpgc-cte
def user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user pastes 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 pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=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

0 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
    def get_context_data(self, **kwargs):
        context = super(PastwordResetCompleteView, self).get_context_data(**kwargs)
        context['login_url'] = resolve_url(settings.LOGIN_URL)
        return context

0 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : edisonlz
def user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user pastes 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 pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=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()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                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

0 View Complete Implementation : auth.py
Copyright GNU General Public License v3.0
Author : forcemain
    def handle_unauthenticated_user(self):
        nxt = '{0}?{1}'.format(self.request.path, urllib.urlencode([('request_token', self.cas_token.request_token)]))
        url = '{0}?{1}'.format(settings.LOGIN_URL, urllib.urlencode([('next', nxt)]))

        return HttpResponseRedirect(url)

0 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : geekwolf
def login(request):

    if request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.method == 'GET':
        next = request.path
        if next == settings.LOGIN_URL:
            next = '/'
        return render_to_response('accounts/login.html',{'next':next})

    if request.method == "POST":
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            auth.login(request, form.get_user())
            return HttpResponseRedirect(request.POST['next'])
        else:
            error = form.errors
    else:
        form = LoginForm(request)
    data = {'request': request,'form':  form, 'error': error}
    return render_to_response('accounts/login.html', data)

0 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : geekwolf
def logout(request):
    
    auth.logout(request)
    return HttpResponseRedirect(settings.LOGIN_URL)

0 View Complete Implementation : tests.py
Copyright BSD 2-Clause "Simplified" License
Author : jambonsw
    def test_pastword_change(self):
        """Simulate a user changing their pastword"""
        email = '[email protected]'
        pastword = 's4f3pastw0rd!'
        newpastword = 'neo.h1m1tsu!'
        User = get_user_model()  # pylint: disable=invalid-name
        User.objects.create_user(email, pastword)

        response = self.client.get(reverse('pastword_change'))
        self.astertRedirects(
            response,
            '{}?next={}'.format(
                reverse(settings.LOGIN_URL), reverse('pastword_change')))
        self.client.login(username=email, pastword=pastword)
        response = self.client.get(reverse('pastword_change'))
        # WARNING:
        # this uses Django's admin template
        # to change this behavior, place user_integration app before
        # the admin app in the INSTALLED_APPS settings
        self.astertTemplateUsed(
            response, 'registration/pastword_change_form.html')

        data = {
            'old_pastword': pastword,
            'new_pastword1': newpastword,
            'new_pastword2': newpastword,
        }
        response = self.client.post(
            reverse('pastword_change'), data=data, follow=True)
        self.astertRedirects(response, reverse('pastword_change_done'))
        self.astertEqual(response.status_code, 200)
        # WARNING:
        # this uses Django's admin template
        # to change this behavior, place user_integration app before
        # the admin app in the INSTALLED_APPS settings
        self.astertTemplateUsed(
            response, 'registration/pastword_change_done.html')

        self.client.logout()
        self.astertTrue(
            self.client.login(username=email, pastword=newpastword))

0 View Complete Implementation : LoginMiddleWare.py
Copyright MIT License
Author : LianjiaTech
    def process_request(self, request):
        requestUrl = request.path
        addUserLog(request, "MiddleWare", "Past")
        needFilt = True
        if requestUrl==settings.LOGIN_URL:
            needFilt = False
        else:
            for noAuthUrl in settings.NO_AUTH_URLS:
                if requestUrl.startswith(noAuthUrl):
                    needFilt = False
                    break
        if needFilt:
            adminFilt = False
            for adminAuthUrl in settings.MYADMIN_URLS:
                if requestUrl.startswith(adminAuthUrl):
                    adminFilt = True
                    break
            if adminFilt:
                adminAuthInfo = adminAAA(request)
                if adminAuthInfo[0] == False:
                    return doLogin(request)
            else:
                authInfo = AAAUser(request)
                redirectUrlList = [
                    "/interfaceTest/HTTP_InterfaceCheck",
                    "/dubbo/interfaceList",
                    "/mockserver/HTTP_InterfaceCheck",
                    "/interfaceTest/HTTP_operationInterface",
                    "/interfaceTest/HTTP_InterfaceAddPage",
                    "/interfaceTest/importPostmanPage",
                    "/dubbo/importLogPage",
                    "/interfaceTest/HTTP_TestCaseCheck",
                    "/interfaceTest/HTTP_TestCaseStepCheck",
                    "/interfaceTest/HTTP_TestCaseAddPage",
                    "/interfaceTest/HTTP_TaskCheck",
                    "/interfaceTest/HTTP_TaskSuiteCheck",
                    "/dubbo/operationInterface",
                    "/dubbo/interfaceAddPage",
                    "/statistictask/execlistPage",
                    "/statistictask/listPage",
                    "/statistictask/operationCheck",
                    "/interfaceTest/HTTP_EnvUriConf",
                    "/interfaceTest/HTTP_UserHttpConf",
                    "/interfaceTest/HTTP_UriConf",
                    "/interfaceTest/HTTP_UserServiceConf",
                    "/interfaceTest/HTTP_GlobalVarsConf",
                    "/interfaceTest/HTTP_GlobalTextConf",
                    "/datakeyword/listPage",
                    "/datakeyword/operationCheck",
                    "/interfaceTest/HTTP_operationTestCase",
                    "/dubbo/operationTestCase",
                ]
                if request.META["PATH_INFO"] in  redirectUrlList:
                    request.session["nextUrl"] = request.META["PATH_INFO"] + ("" if request.META["QUERY_STRING"] == "" else "?"+request.META["QUERY_STRING"])
                if authInfo[0] == False:
                    return index(request)

0 View Complete Implementation : base.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def _redirect_to_login(self, next_url, login_url, redirect_field_name):
        '''
        preserve fragment after #
        '''

        # TODO
        from django.shortcuts import resolve_url
        from urllib.parse import urlparse, urlunparse
        from django.http import QueryDict

        resolved_url = resolve_url(login_url or settings.LOGIN_URL)
        login_url_parts = list(urlparse(resolved_url))
        # scheme='', netloc='', path='/_/', params='', query='', fragment='/oneid/login'
        # -> 
        # scheme='', netloc='', path='/_/#/oneid/login', params='', query='', fragment=''
        login_url_parts[2] += '#{}'.format(login_url_parts[5])
        login_url_parts[5] = ''
        if redirect_field_name:
            querystring = QueryDict(login_url_parts[4], mutable=True)
            querystring[redirect_field_name] = next_url
            login_url_parts[4] = querystring.urlencode(safe='/')

        return HttpResponseRedirect(urlunparse(login_url_parts))

0 View Complete Implementation : views.py
Copyright MIT License
Author : MicroPyramid
    def dispatch(self, request, *args, **kwargs):
        self.user = self.get_user()
        if self.user is None:
            return HttpResponseRedirect(settings.LOGIN_URL)
        return super(VerifySecondFactorView, self).dispatch(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright MIT License
Author : rodrigosetti
def coding_problem(request, slug):
    problem = CodingProblem.objects.get(slug=slug)
    user = request.user

    if request.method == 'POST':
        if not user.is_authenticated:
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(settings.LOGIN_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()
            return redirect_to_login(path,
                                     resolved_login_url,
                                     REDIRECT_FIELD_NAME)

        submission = CodeSubmission(
            problem=problem,
            user=user)
        submission_form = CodeSubmissionForm(request.POST, instance=submission)
        if submission_form.is_valid():
            submission_form.save()

            # send task
            judge_code_submission.delay(submission.id)

            # keep only the top 10 submissions
            for n, s in enumerate(CodeSubmission.objects.filter(user=user, problem=problem).order_by("submission_time").reverse()):
                if n >= 10:
                    s.delete()

            messages.success(request,
                             _('Your code was successfully submitted'))
            return redirect('coding-problem-detail', slug)
        else:
            messages.error(request,
                           _('Please correct the error below.'))
    else:
        submission_form = CodeSubmissionForm()

        if user.is_authenticated:
            submissions = problem.user_submissions(user)
            try:
                latest_submission = submissions.earliest()
                submission_form.initial["language"] = latest_submission.language
                submission_form.initial["code"] = latest_submission.code
            except CodeSubmission.DoesNotExist:
                past
        else:
            submissions = []

        return render(request, 'candidates/codingproblem_detail.html', {
            'problem': problem,
            'submission_form': submission_form,
            'examples': problem.examples,
            'submissions': submissions
        })

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : rizwansoaib
def user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user pastes 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 pastes.
    """

    def decorator(view_func):
        @wraps(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

0 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['login_url'] = resolve_url(settings.LOGIN_URL)
        return context

0 View Complete Implementation : generics.py
Copyright MIT License
Author : sanoma
    def dispatch(self, request, *args, **kwargs):
        """
        Most views in a CMS require a login, so this is the default setup.

        If a login is not required then the requires_login property
        can be set to False to disable this.
        """
        if self.requires_login:
            if settings.LOGIN_URL is None or settings.LOGOUT_URL is None:
                raise ImproperlyConfigured(
                    "LOGIN_URL and LOGOUT_URL "
                    "has to be defined if requires_login is True"
                )

            if not request.user.is_authenticated:
                return redirect(
                    "%s?next=%s"
                    % (
                        resolve_url(settings.LOGIN_URL),
                        quote(request.get_full_path()),
                    )
                )

        return super(View, self).dispatch(request, *args, **kwargs)

0 View Complete Implementation : generics.py
Copyright MIT License
Author : sanoma
    def dispatch(self, request, *args, **kwargs):
        logout(request)
        return redirect(settings.LOGIN_URL)

0 View Complete Implementation : decorators.py
Copyright GNU Affero General Public License v3.0
Author : SpottedBot
def custom_user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """Custom user pastes test.

    Decorator for views that checks that the user pastes 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 pastes.
    """
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            if request.user.is_authenticated:
                messages.add_message(request, messages.ERROR, 'Você não tem permissão para isso!')
                login_url = '/'
            else:
                login_url = None
            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