Python django.conf.settings.LOGIN_REDIRECT_URL Examples

The following are 30 code examples of django.conf.settings.LOGIN_REDIRECT_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: views.py    From simple-django-login-and-register with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def form_valid(self, form):
        request = self.request

        # If the test cookie worked, go ahead and delete it since its no longer needed
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()

        # The default Django's "remember me" lifetime is 2 weeks and can be changed by modifying
        # the SESSION_COOKIE_AGE settings' option.
        if settings.USE_REMEMBER_ME:
            if not form.cleaned_data['remember_me']:
                request.session.set_expiry(0)

        login(request, form.user_cache)

        redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))
        url_is_safe = is_safe_url(redirect_to, allowed_hosts=request.get_host(), require_https=request.is_secure())

        if url_is_safe:
            return redirect(redirect_to)

        return redirect(settings.LOGIN_REDIRECT_URL) 
Example #2
Source File: views.py    From ldap-oauth2 with 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 #3
Source File: views.py    From django-mfa with 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 #4
Source File: views.py    From django-mfa with 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 #5
Source File: test_views.py    From djongo with 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 #6
Source File: tests.py    From ANALYSE with 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 #7
Source File: test_views.py    From djongo with 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 #8
Source File: test_views.py    From djongo with 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 #9
Source File: views.py    From django-leonardo with 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 #10
Source File: views.py    From djacket with 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 #11
Source File: tests.py    From django_cve_2019_19844_poc with 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 #12
Source File: decorators.py    From django-shopify-auth with 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 #13
Source File: viste.py    From jorvik with 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 #14
Source File: account_views.py    From open-humans with 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 #15
Source File: views.py    From cryptofolio with GNU General Public License v3.0 5 votes vote down vote up
def login(request):
    redirect_to = request.GET.get(REDIRECT_FIELD_NAME, '')

    if request.method == "POST":
        form = AuthenticationForm(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(django_settings.LOGIN_REDIRECT_URL)

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

            return HttpResponseRedirect(redirect_to)
        else:
            messages.warning(request, 'Wrong username and/or password!')
    else:
        form = AuthenticationForm(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        REDIRECT_FIELD_NAME: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }

    return render(request, 'login.html', context) 
Example #16
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_user_home(self, user):
        """Returns the default URL for a particular user.

        This method can be used to customize where a user is sent when
        they log in, etc. By default it returns the value of
        :meth:`get_absolute_url`.

        An alternative function can be supplied to customize this behavior
        by specifying a either a URL or a function which returns a URL via
        the ``"user_home"`` key in ``HORIZON_CONFIG``. Each of these
        would be valid::

            {"user_home": "/home",}  # A URL
            {"user_home": "my_module.get_user_home",}  # Path to a function
            {"user_home": lambda user: "/" + user.name,}  # A function
            {"user_home": None,}  # Will always return the default dashboard

        This can be useful if the default dashboard may not be accessible
        to all users. When user_home is missing from HORIZON_CONFIG,
        it will default to the settings.LOGIN_REDIRECT_URL value.
        """
        user_home = self._conf['user_home']
        if user_home:
            if callable(user_home):
                return user_home(user)
            elif isinstance(user_home, basestring):
                # Assume we've got a URL if there's a slash in it
                if '/' in user_home:
                    return user_home
                else:
                    mod, func = user_home.rsplit(".", 1)
                    return getattr(import_module(mod), func)(user)
            # If it's not callable and not a string, it's wrong.
            raise ValueError('The user_home setting must be either a string '
                             'or a callable object (e.g. a function).')
        else:
            return self.get_absolute_url() 
Example #17
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_login_form_contains_request(self):
        # The custom authentication form for this login requires a request to
        # initialize it.
        response = self.client.post('/custom_request_auth_login/', {
            'username': 'testclient',
            'password': 'password',
        })
        # The login was successful.
        self.assertRedirects(response, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) 
Example #18
Source File: auth_view.py    From eoj3 with MIT License 5 votes vote down vote up
def _get_login_redirect_url(request, redirect_to):
  # Ensure the user-originating redirection URL is safe.
  if not is_safe_url(url=redirect_to, allowed_hosts=request.get_host()):
    return resolve_url(settings.LOGIN_REDIRECT_URL)
  return redirect_to 
Example #19
Source File: views.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def dc_switch_form(request):
    """
    Ajax page for changing current working datacenter.
    """
    form = DcSwitch(request, request.POST, prefix='dc')

    if form.is_valid():
        if form.save():
            return redirect(form.get_referrer() or settings.LOGIN_REDIRECT_URL)
        else:
            return HttpResponse(None, status=204)

    return render(request, 'gui/dc/dc_switch_form.html', {'dcs_form': form}) 
Example #20
Source File: auth_view.py    From eoj3 with MIT License 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, redirect_authenticated_user=False):
  """
  Displays the login form and handles the login action.
  """
  redirect_to = request.GET.get(redirect_field_name, request.POST.get(redirect_field_name, ''))

  if redirect_authenticated_user and request.user.is_authenticated:
    redirect_to = _get_login_redirect_url(request, redirect_to)
    if redirect_to == 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)
  elif request.method == "POST":
    form = authentication_form(request, data=request.POST)
    if form.is_valid():
      auth_login(request, form.get_user())
      request.session.set_expiry(None if form.cleaned_data['remember_me'] else 0)
      return HttpResponseRedirect(_get_login_redirect_url(request, 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 #21
Source File: utils.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def impersonate_user(request, user_id):
    if not request.user.is_staff:
        raise PermissionDenied

    request.session['impersonate_id'] = user_id

    return redirect(settings.LOGIN_REDIRECT_URL) 
Example #22
Source File: adapters.py    From open-humans with MIT License 5 votes vote down vote up
def get_connect_redirect_url(self, request, socialaccount):
        """
        We want to redirect based on what is set in the session rather than
        use the default method of passing a ?next= parameter on the URL.
        """
        assert request.user.is_authenticated
        path = request.session.pop("next_url", reverse(settings.LOGIN_REDIRECT_URL))
        return path 
Example #23
Source File: views.py    From django-mfa with MIT License 5 votes vote down vote up
def verify_second_factor_totp(request):
    """
    Verify a OTP request
    """
    ctx = {}
    if request.method == 'GET':
        ctx['next'] = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
        return render(request, 'django_mfa/verify_second_factor_mfa.html', ctx)

    if request.method == "POST":
        verification_code = request.POST.get('verification_code')
        ctx['next'] = request.POST.get("next", settings.LOGIN_REDIRECT_URL)

        if verification_code is None:
            ctx['error_message'] = "Missing verification code."

        else:
            user_recovery_codes = UserRecoveryCodes.objects.values_list('secret_code', flat=True).filter(
                user=UserOTP.objects.get(user=request.user.id))
            if verification_code in user_recovery_codes:
                UserRecoveryCodes.objects.filter(user=UserOTP.objects.get(
                    user=request.user.id), secret_code=verification_code).delete()
                is_verified = True
            else:
                otp_ = UserOTP.objects.get(user=request.user)
                totp_ = totp.TOTP(otp_.secret_key)

                is_verified = totp_.verify(verification_code)

            if is_verified:
                request.session['verfied_otp'] = True
                request.session['verfied_u2f'] = True
                response = redirect(request.POST.get(
                    "next", settings.LOGIN_REDIRECT_URL))
                return update_rmb_cookie(request, response)
            ctx['error_message'] = "Your code is expired or invalid."
    else:
        ctx['next'] = request.GET.get('next', settings.LOGIN_REDIRECT_URL)

    return render(request, 'django_mfa/verify_second_factor_mfa.html', ctx, status=400) 
Example #24
Source File: views.py    From django-mfa with MIT License 5 votes vote down vote up
def security_settings(request):
    twofactor_enabled = is_mfa_enabled(request.user)
    u2f_enabled = is_u2f_enabled(request.user)
    backup_codes = UserRecoveryCodes.objects.filter(
        user=UserOTP.objects.filter(user=request.user).first()).all()
    return render(request, 'django_mfa/security.html', {"prev_url": settings.LOGIN_REDIRECT_URL, "backup_codes": backup_codes, "u2f_enabled": u2f_enabled, "twofactor_enabled": twofactor_enabled}) 
Example #25
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" 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 #26
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" 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 #27
Source File: views.py    From django-oidc-auth with MIT License 5 votes vote down vote up
def _redirect(request, login_complete_view, form_class, redirect_field_name):
    provider = get_default_provider()

    if not provider:
        form = form_class(request.POST)

        if not form.is_valid():
            raise errors.MissingRedirectURL()

        provider = OpenIDProvider.discover(issuer=form.cleaned_data['issuer'])

    redirect_url = request.GET.get(redirect_field_name, settings.LOGIN_REDIRECT_URL)
    nonce = Nonce.generate(redirect_url, provider.issuer)
    request.session['oidc_state'] = nonce.state

    params = urlencode({
        'response_type': 'code',
        'scope': utils.scopes(),
        # 'redirect_uri': request.build_absolute_uri(reverse(login_complete_view)),
        'client_id': provider.client_id,
        'state': nonce.state
    })
    redirect_url = '%s?%s' % (provider.authorization_endpoint, params)

    log.debug('Redirecting to %s' % redirect_url)
    return redirect(redirect_url) 
Example #28
Source File: pdctags.py    From product-definition-center with MIT License 5 votes vote down vote up
def login_url(redirect=None):
    """Create login url based on settings.

    Optionally, append redirection URL.
    """
    url = settings.LOGIN_URL
    redirect = redirect or settings.LOGIN_REDIRECT_URL
    if redirect:
        url += '?next=' + redirect
    return url 
Example #29
Source File: views.py    From django-shopify-auth with MIT License 5 votes vote down vote up
def get_return_address(request):
    return request.session.get(SESSION_REDIRECT_FIELD_NAME) or request.GET.get(auth.REDIRECT_FIELD_NAME) or resolve_url(settings.LOGIN_REDIRECT_URL) 
Example #30
Source File: test_views.py    From djangoecommerce with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_login_ok(self):
        response = self.client.get(self.login_url)
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'login.html')
        data = {'username': self.user.username, 'password': '123'}
        response = self.client.post(self.login_url, data)
        redirect_url = reverse(settings.LOGIN_REDIRECT_URL)
        self.assertRedirects(response, redirect_url)
        self.assertTrue(response.wsgi_request.user.is_authenticated())