Example #1
0
def get_page_and_links(request, qs, find_expression=FIND_EXPRESSION):
    per_page = int(request.GET.get('per_page', DEFAULT_PER_PAGE))
    per_page = max(MIN_PER_PAGE, per_page)
    paginator = Paginator(qs, per_page)

    page = request.GET.get('page')
    try:
        page = paginator.page(page)
    except PageNotAnInteger:
        page = paginator.page(1)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)

    page_base_url = "%s%s" % (get_base_url(request), request.path)
    self_url = update_url(page_base_url, request.GET)
    links = {
        'find': {'href': '%s%s' % (page_base_url, find_expression), 'templated': True},
        'self': {'href': self_url}
    }

    if page.has_next():
        links['next'] = {'href': update_url(self_url, {'page': page.next_page_number()})}
    if page.has_previous():
        links['prev'] = {'href': update_url(self_url, {'page': page.previous_page_number()})}

    return page, links
Example #2
0
    def get_data(self, context):
        page_base_url = "%s%s" % (get_base_url(
            self.request), self.request.path)
        self_url = update_url(page_base_url, self.request.GET)
        data = {
            'member': [
                self.get_object_data(self.request, obj)
                for obj in context['object_list']
            ],
            'total_items':
            context['paginator'].count
        }
        if context['is_paginated']:
            data['items_per_page'] = context['paginator'].per_page

            page = context['page_obj']
            if page.has_next():
                data['next_page'] = update_url(
                    self_url, {'page': page.next_page_number()})
            if page.has_previous():
                data['prev_page'] = update_url(
                    self_url, {'page': page.previous_page_number()})

        data['@id'] = self_url
        data['operation'] = self.get_allowed_operations(None)
        return data
Example #3
0
File: profile.py Project: g10f/sso
def password_change(request):
    """
    Handles the "change password" task -- both form display and validation.
    """
    redirect_uri = get_safe_redirect_uri(request, allowed_hosts())
    post_change_redirect = update_url(reverse('accounts:password_change_done'),
                                      {'redirect_uri': redirect_uri})
    template_name = 'accounts/password_change_form.html'
    if request.method == "POST":
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            # Updating the password logs out all other sessions for the user
            # except the current one
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = PasswordChangeForm(user=request.user)
    context = {
        'password_validators_help_texts': password_validators_help_texts(),
        'form': form,
        'title': _('Password change'),
        'redirect_uri': redirect_uri
    }

    return TemplateResponse(request, template_name, context)
Example #4
0
File: __init__.py Project: g10f/sso
def logout(request, next_page=None,
           template_name='sso_auth/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
    """
    # save the user
    user = request.user
    auth_logout(request)
    # 1. check if we have a post_logout_redirect_uri which is registered
    redirect_to = settings.LOGIN_REDIRECT_URL
    redirect_uri = get_request_param(request, OIDC_LOGOUT_REDIRECT_FIELD_NAME)
    allowed_schemes = ['http', 'https']
    if redirect_uri:
        id_token = get_request_param(request, OIDC_ID_TOKEN_HINT)
        if id_token:
            # token maybe expired
            data = loads_jwt(id_token, options={"verify_exp": False, "verify_aud": False})
            if user.is_anonymous or user.uuid == UUID(data['sub']):
                client = Client.objects.get(uuid=data['aud'])
                if redirect_uri in client.post_logout_redirect_uris.split():
                    # allow unsafe schemes
                    redirect_to = redirect_uri
                    allowed_schemes = None
        else:
            # if no OIDC_ID_TOKEN_HINT is there, allow only safe schemes
            if redirect_uri in post_logout_redirect_uris():
                redirect_to = redirect_uri
        redirect_to = update_url(redirect_to, {OIDC_STATE: get_request_param(request, OIDC_STATE)})
        return HttpPostLogoutRedirect(redirect_to=redirect_to, allowed_schemes=allowed_schemes)
    else:
        # deprecated logic
        redirect_uris = [redirect_field_name, REDIRECT_URI_FIELD_NAME, OIDC_LOGOUT_REDIRECT_FIELD_NAME]
        redirect_to = get_safe_redirect_uri(request, allowed_hosts(), redirect_uris)
        if redirect_to:
            return HttpPostLogoutRedirect(redirect_to=redirect_to, allowed_schemes=['http', 'https'])

    if next_page is None:
        current_site = get_current_site(request)
        site_name = settings.SSO_SITE_NAME
        context = {
            'site': current_site,
            'site_name': site_name,
            'title': _('Logged out')
        }
        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)
    else:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page or request.path)
Example #5
0
File: profile.py Project: g10f/sso
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     uidb64 = kwargs.get('uidb64')
     if uidb64 is not None:
         app = get_start_app(uidb64)
         if app:
             login_url = resolve_url(settings.LOGIN_URL)
             context['login_url'] = update_url(
                 login_url, {REDIRECT_FIELD_NAME: app.url})
             context['app'] = app
     return context
Example #6
0
    def get_data(self, context):
        data = self.get_object_data(self.request, context['object'])

        if '@id' not in data:
            # if no @id is there we use the current url as the default
            page_base_url = "%s%s" % (get_base_url(
                self.request), self.request.path)
            data['@id'] = update_url(page_base_url, self.request.GET)

        data['operation'] = self.get_allowed_operations(context['object'])
        return data
Example #7
0
def otp_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in with 2FA, redirecting
    to the log-in page if necessary.
    """
    if login_url is None:
        login_url = update_url(reverse_lazy('login'), {TWO_FACTOR_PARAM: '1'})
    test = lambda u: u.is_authenticated and u.is_verified
    actual_decorator = user_passes_test(
        test,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator
Example #8
0
File: profile.py Project: g10f/sso
def get_profile_success_url(request, redirect_uri):
    if "_continue" in request.POST:
        if redirect_uri:
            success_url = update_url(reverse('accounts:profile'),
                                     {'redirect_uri': redirect_uri})
        else:
            success_url = reverse('accounts:profile')
        messages.success(
            request,
            _('Your profile was changed successfully. You may edit it again below.'
              ))
    else:
        if redirect_uri:
            success_url = redirect_uri
        else:
            success_url = reverse('home')
            messages.success(request, _('Thank you. Your profile was saved.'))

    return success_url
Example #9
0
File: profile.py Project: g10f/sso
def emails(request):
    redirect_uri = get_safe_redirect_uri(request, allowed_hosts())
    post_change_redirect = update_url(reverse('accounts:emails'),
                                      {'redirect_uri': redirect_uri})

    user = request.user
    if request.method == 'POST':
        if 'send_confirmation' in request.POST:
            user_email = UserEmail.objects.get(
                id=request.POST['send_confirmation'])
            send_useremail_confirmation(user_email, request)
            messages.success(
                request,
                _('Confirmation email was sent to \"%(email)s\".') %
                {'email': user_email})
            return redirect(post_change_redirect)
        elif 'delete' in request.POST:
            try:
                user_email = UserEmail.objects.get(id=request.POST['delete'])
                user_email.delete()
                messages.success(
                    request,
                    _('The email \"%(email)s\" was deleted successfully.') %
                    {'email': user_email})
            except UserEmail.DoesNotExist:
                # may be a double click on the delete button
                pass
            return redirect(post_change_redirect)
        elif 'set_primary' in request.POST:
            user_email = UserEmail.objects.get(id=request.POST['set_primary'])
            user_email.primary = True
            user_email.save()
            UserEmail.objects.filter(
                user=user_email.user,
                primary=True).exclude(pk=user_email.pk).update(primary=False)
            messages.success(
                request,
                _("The email \"%(email)s\" was changed successfully.") %
                {'email': user_email})
            return redirect(post_change_redirect)
        else:
            add_form = SelfUserEmailAddForm(request.POST)
            if add_form.is_valid():
                user_email = add_form.save()
                change_message = ChangedDataList(add_form, []).change_message()
                log_change(request, user, change_message)
                msg = _('Thank you. Your data were saved.') + '\n'
                msg += _('Confirmation email was sent to \"%(email)s\".') % {
                    'email': user_email
                }
                messages.success(request, msg)
                send_useremail_confirmation(user_email, request)
                return redirect(post_change_redirect)
    else:
        add_form = SelfUserEmailAddForm(initial={'user': user.id})

    context = {
        'form': add_form,
        'max_email_adresses': UserEmail.MAX_EMAIL_ADRESSES,
        'redirect_uri': redirect_uri
    }
    return render(request, 'accounts/user_email_detail.html', context)