Python django.conf.settings.LOGIN_REDIRECT_URL Examples

The following are 30 code examples for showing how to use django.conf.settings.LOGIN_REDIRECT_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
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
Project: djacket   Author: Djacket   File: views.py    License: MIT License 6 votes vote down vote up
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 3
Project: django-leonardo   Author: django-leonardo   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dispatch(self, request, uidb36, key, **kwargs):
        self.request = request
        self.key = key
        # (Ab)using forms here to be able to handle errors in XHR #890
        token_form = UserTokenForm(data={'uidb36': uidb36, 'key': key})

        if not token_form.is_valid():
            self.reset_user = None
            messages.error(
                self.request, _('Token is invalid !'))
            return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        else:
            self.reset_user = token_form.reset_user
            return super(ResetPasswordKeyView, self).dispatch(request,
                                                              uidb36,
                                                              key,
                                                              **kwargs) 
Example 4
Project: ANALYSE   Author: jruiperezv   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_inactive_session_timeout(self):
        """
        Verify that an inactive session times out and redirects to the
        login page
        """
        self.create_account(self.username, self.email, self.pw)
        self.activate_user(self.email)

        self.login(self.email, self.pw)

        # make sure we can access courseware immediately
        course_url = '/course/'
        resp = self.client.get_html(course_url)
        self.assertEquals(resp.status_code, 200)

        # then wait a bit and see if we get timed out
        time.sleep(2)

        resp = self.client.get_html(course_url)

        # re-request, and we should get a redirect to login page
        self.assertRedirects(resp, settings.LOGIN_REDIRECT_URL + '?next=/course/') 
Example 5
Project: ldap-oauth2   Author: DheerendraRathor   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        form = self.form_class(request.POST)
        next_ = request.POST.get('next', settings.LOGIN_REDIRECT_URL)
        if next_ == '':
            next_ = settings.LOGIN_REDIRECT_URL
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            remember = form.cleaned_data['remember']

            user = authenticate(username=username, password=password)
            if user is not None:
                if remember:
                    # Yearlong Session
                    request.session.set_expiry(24 * 365 * 3600)
                else:
                    request.session.set_expiry(0)
                login(request, user)
                return redirect(next_)
            else:
                form.add_error(None, "Unable to authorize user. Try again!")
        return render(request, self.template_name, {'form': form}) 
Example 6
Project: open-humans   Author: OpenHumans   File: account_views.py    License: MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        default_redirect = reverse(settings.LOGIN_REDIRECT_URL)
        raw_url = request.POST.get("next_url", default_redirect)
        # Using window.location.href on the js side gives full domain + path,
        # and we only want the path
        parsed_url = urlparse(raw_url)
        path = parsed_url.path
        params = parsed_url.query
        if params:
            next_t = "{0}?{1}".format(path, params)
        else:
            next_t = path
        # In case someone tries to login from the signup page, it would
        # have a circular redirect, so we leave the session alone
        login_or_signup = (reverse("account_login") in path) or (
            reverse("account_signup") in path
        )
        if not login_or_signup:
            request.session["next_url"] = next_t
        # Complains if we don't explicitely return an HttpResponse, so send
        # an empty one.
        return HttpResponse("") 
Example 7
Project: django-shopify-auth   Author: discolabs   File: decorators.py    License: MIT License 6 votes vote down vote up
def anonymous_required(function=None, redirect_url=None):
    """
    Decorator requiring the current user to be anonymous (not logged in).
    """
    if not redirect_url:
        redirect_url = settings.LOGIN_REDIRECT_URL

    actual_decorator = user_passes_test(
        is_anonymous,
        login_url=redirect_url,
        redirect_field_name=None
    )

    if function:
        return actual_decorator(function)
    return actual_decorator 
Example 8
Project: django-mfa   Author: MicroPyramid   File: views.py    License: MIT License 6 votes vote down vote up
def index(request):
    if request.user and request.user.is_authenticated:
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
    if request.method == 'POST':
        form = LoginForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.user
            if is_u2f_enabled(user):
                request.session['u2f_pre_verify_user_pk'] = user.pk
                request.session['u2f_pre_verify_user_backend'] = user.backend
            login(request, form.user)
            return JsonResponse({"error": False})
        else:
            return JsonResponse({"error": True, "errors": form.errors})
    context = {
        "registration_form": RegistrationForm,
        "login_form": LoginForm
    }
    return render(request, 'login.html', context) 
Example 9
Project: django-mfa   Author: MicroPyramid   File: views.py    License: MIT License 6 votes vote down vote up
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 10
Project: djongo   Author: nesdis   File: test_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_security_check_https(self):
        login_url = reverse('login')
        non_https_next_url = 'http://testserver/path'
        not_secured_url = '%(url)s?%(next)s=%(next_url)s' % {
            'url': login_url,
            'next': REDIRECT_FIELD_NAME,
            'next_url': quote(non_https_next_url),
        }
        post_data = {
            'username': 'testclient',
            'password': 'password',
        }
        response = self.client.post(not_secured_url, post_data, secure=True)
        self.assertEqual(response.status_code, 302)
        self.assertNotEqual(response.url, non_https_next_url)
        self.assertEqual(response.url, settings.LOGIN_REDIRECT_URL) 
Example 11
Project: djongo   Author: nesdis   File: test_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_redirect_loop(self):
        """
        Detect a redirect loop if LOGIN_REDIRECT_URL is not correctly set,
        with and without custom parameters.
        """
        self.login()
        msg = (
            "Redirection loop for authenticated user detected. Check that "
            "your LOGIN_REDIRECT_URL doesn't point to a login page"
        )
        with self.settings(LOGIN_REDIRECT_URL=self.do_redirect_url):
            with self.assertRaisesMessage(ValueError, msg):
                self.client.get(self.do_redirect_url)

            url = self.do_redirect_url + '?bla=2'
            with self.assertRaisesMessage(ValueError, msg):
                self.client.get(url) 
Example 12
Project: djongo   Author: nesdis   File: test_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_security_check_https(self):
        login_url = reverse('login')
        non_https_next_url = 'http://testserver/path'
        not_secured_url = '%(url)s?%(next)s=%(next_url)s' % {
            'url': login_url,
            'next': REDIRECT_FIELD_NAME,
            'next_url': quote(non_https_next_url),
        }
        post_data = {
            'username': 'testclient',
            'password': 'password',
        }
        response = self.client.post(not_secured_url, post_data, secure=True)
        self.assertEqual(response.status_code, 302)
        self.assertNotEqual(response.url, non_https_next_url)
        self.assertEqual(response.url, settings.LOGIN_REDIRECT_URL) 
Example 13
Project: django_cve_2019_19844_poc   Author: ryu22e   File: tests.py    License: MIT License 6 votes vote down vote up
def test_redirect_to_index_after_login(self):
        username = 'taro'
        email = 'taro@example.com'
        password = 'testpassword'
        self._create_user(
            username=username,
            email=email,
            password=password,
        )
        data = {
            'username': username,
            'password': password,
        }
        r = self.client.post(reverse('accounts:login'), data)
        self.assertRedirects(
            r,
            settings.LOGIN_REDIRECT_URL,
            fetch_redirect_response=False,
        ) 
Example 14
Project: jorvik   Author: CroceRossaItaliana   File: viste.py    License: GNU General Public License v3.0 6 votes vote down vote up
def done(self, form_list, **kwargs):
        """
        Login the user and redirect to the desired page.
        """
        login(self.request, self.get_user())

        redirect_to = self.request.GET.get(self.redirect_field_name, '')
        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
        if self.get_user().richiedi_attivazione_2fa:
            redirect_to = resolve_url(settings.TWO_FACTOR_PROFILE)

        device = getattr(self.get_user(), 'otp_device', None)
        if device:
            signals.user_verified.send(sender=__name__, request=self.request,
                                       user=self.get_user(), device=device)
        return redirect(redirect_to) 
Example 15
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context) 
Example 16
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def done(self, form_list, **kwargs):
            """
            Login the user and redirect to the desired page.
            """
            login(self.request, self.get_user())

            redirect_to = self.request.POST.get(
                self.redirect_field_name,
                self.request.GET.get(self.redirect_field_name, '')
            )
            if not is_safe_url(url=redirect_to, host=self.request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            is_auth = False
            user = self.get_user()
            device = getattr(self.get_user(), 'otp_device', None)
            if device:
                signals.user_verified.send(sender=__name__, request=self.request,
                                           user=self.get_user(), device=device)
                redirect_to = resolve_url("dashboard:main")
                is_auth = True
            elif ENFORCE_2FA:
                redirect_to = resolve_url("two_factor:profile")
            else:
                redirect_to = resolve_url("dashboard:main")
                is_auth = True
            if not self.request.POST.get('remember', None):
                self.request.session.set_expiry(0)
            try:
                Profile.objects.get(user=user)
            except ObjectDoesNotExist:
                profile = Profile()
                profile.user = user
                profile.hide_closed = False
                profile.incident_number = 50
                profile.save()
            if user.is_active:
                log("Login success", user)
                init_session(self.request)
            return redirect(redirect_to) 
Example 17
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            redirect_to = self.get_success_url()
            if redirect_to == self.request.path:
                raise ValueError(
                    "Redirection loop for authenticated user detected. Check that "
                    "your LOGIN_REDIRECT_URL doesn't point to a login page."
                )
            return HttpResponseRedirect(redirect_to)
        return super().dispatch(request, *args, **kwargs) 
Example 18
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 5 votes vote down vote up
def get_success_url(self):
        url = self.get_redirect_url()
        return url or resolve_url(settings.LOGIN_REDIRECT_URL) 
Example 19
def dispatch(self, request, *args, **kwargs):
        # Redirect to the index page if the user already authenticated
        if request.user.is_authenticated:
            return redirect(settings.LOGIN_REDIRECT_URL)

        return super().dispatch(request, *args, **kwargs) 
Example 20
Project: djacket   Author: Djacket   File: decorators.py    License: MIT License 5 votes vote down vote up
def redirect_if_authorized(func):
    """
        Redirects user to the given view (identified by 'view_name' parameter)
            if user is authenticated.
    """

    @wraps(func)
    def _decorator(request, *args, **kwargs):
        if request.user.is_authenticated():
            return redirect(settings.LOGIN_REDIRECT_URL)
        else:
            return func(request, *args, **kwargs)
    return _decorator 
Example 21
Project: djacket   Author: Djacket   File: views.py    License: MIT License 5 votes vote down vote up
def user_register(request):
    """
        View for registering new users. If user is already authenticated view redirects
            to index page.
    """

    register_form = UserRegistrationForm(request.POST)
    if register_form.is_valid():
        register_form.save()
        registered_user = authenticate(username=register_form.cleaned_data['username'],
                                    password=register_form.cleaned_data['password'])
        auth_login(request, registered_user)
        return redirect(settings.LOGIN_REDIRECT_URL)

    return render(request, 'index.html', {'register_form': register_form, 'display': 'block', 'active': 'register'}) 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            redirect_to = self.get_success_url()
            if redirect_to == self.request.path:
                raise ValueError(
                    "Redirection loop for authenticated user detected. Check that "
                    "your LOGIN_REDIRECT_URL doesn't point to a login page."
                )
            return HttpResponseRedirect(redirect_to)
        return super().dispatch(request, *args, **kwargs) 
Example 23
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def get_success_url(self):
        url = self.get_redirect_url()
        return url or resolve_url(settings.LOGIN_REDIRECT_URL) 
Example 24
Project: django-leonardo   Author: django-leonardo   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        # WORKAROUND: https://code.djangoproject.com/ticket/19316
        self.request = request
        # (end WORKAROUND)
        if request.user.is_authenticated() and \
                settings.LOGIN_REDIRECT_URL:
            return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        else:
            response = super(AuthViewMixin,
                             self).dispatch(request,
                                            *args,
                                            **kwargs)
        return response 
Example 25
Project: django-bootstrap-modal-forms   Author: trco   File: compatibility.py    License: MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            redirect_to = self.get_success_url()
            if redirect_to == self.request.path:
                raise ValueError(
                    'Redirection loop for authenticated user detected. Check that '
                    'your LOGIN_REDIRECT_URL doesn\'t point to a login page.'
                )
            return HttpResponseRedirect(redirect_to)
        return super().dispatch(request, *args, **kwargs) 
Example 26
Project: django-bootstrap-modal-forms   Author: trco   File: compatibility.py    License: MIT License 5 votes vote down vote up
def get_success_url(self):
        url = self.get_redirect_url()
        return url or resolve_url(settings.LOGIN_REDIRECT_URL) 
Example 27
Project: openhgsenti   Author: drexly   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context) 
Example 28
Project: kpi   Author: kobotoolbox   File: __init__.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def one_time_login(request):
    """
    If the request provides a key that matches a OneTimeAuthenticationKey
    object, log in the User specified in that object and redirect to the
    location specified in the 'next' parameter
    """
    try:
        key = request.POST['key']
    except KeyError:
        return HttpResponseBadRequest(_('No key provided'))
    try:
        next_ = request.GET['next']
    except KeyError:
        next_ = None
    if not next_ or not is_safe_url(url=next_, host=request.get_host()):
        next_ = resolve_url(settings.LOGIN_REDIRECT_URL)
    # Clean out all expired keys, just to keep the database tidier
    OneTimeAuthenticationKey.objects.filter(
        expiry__lt=datetime.datetime.now()).delete()
    with transaction.atomic():
        try:
            otak = OneTimeAuthenticationKey.objects.get(
                key=key,
                expiry__gte=datetime.datetime.now()
            )
        except OneTimeAuthenticationKey.DoesNotExist:
            return HttpResponseBadRequest(_('Invalid or expired key'))
        # Nevermore
        otak.delete()
    # The request included a valid one-time key. Log in the associated user
    user = otak.user
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login(request, user)
    return HttpResponseRedirect(next_)


# TODO Verify if it's still used 
Example 29
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            redirect_to = self.get_success_url()
            if redirect_to == self.request.path:
                raise ValueError(
                    "Redirection loop for authenticated user detected. Check that "
                    "your LOGIN_REDIRECT_URL doesn't point to a login page."
                )
            return HttpResponseRedirect(redirect_to)
        return super(LoginView, self).dispatch(request, *args, **kwargs) 
Example 30
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 5 votes vote down vote up
def get_success_url(self):
        url = self.get_redirect_url()
        return url or resolve_url(settings.LOGIN_REDIRECT_URL)