Python django.contrib.auth.decorators.user_passes_test() Examples

The following are 30 code examples of django.contrib.auth.decorators.user_passes_test(). 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.contrib.auth.decorators , or try the search function .
Example #1
Source File: decorators.py    From django-otp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False):
    """
    Similar to :func:`~django.contrib.auth.decorators.login_required`, but
    requires the user to be :term:`verified`. By default, this redirects users
    to :setting:`OTP_LOGIN_URL`.

    :param if_configured: If ``True``, an authenticated user with no confirmed
        OTP devices will be allowed. Default is ``False``.
    :type if_configured: bool
    """
    if login_url is None:
        login_url = settings.OTP_LOGIN_URL

    def test(user):
        return user.is_verified() or (if_configured and user.is_authenticated and not user_has_device(user))

    decorator = user_passes_test(test, login_url=login_url, redirect_field_name=redirect_field_name)

    return decorator if (view is None) else decorator(view) 
Example #2
Source File: decorators.py    From django-uniauth with GNU Lesser General Public License v3.0 6 votes vote down vote up
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME,
        login_url=None):
    """
    Replacement for django's built-in login_required
    decorator that also requires user to not be a
    temporary user (must have completed signup process).

    It can be used identically to the built-in version.
    """
    actual_decorator = user_passes_test(
            lambda u: u.is_authenticated and not is_tmp_user(u),
            login_url=login_url,
            redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #3
Source File: decorators.py    From interop with Apache License 2.0 6 votes vote down vote up
def require_login(func):
    """Decorator to check that user is authenticated before allowing view.

    Raises:
        PermissionDenied: User is not authenticated.
    """
    def check_login(user):
        if not user.is_authenticated:
            raise PermissionDenied('Login required.')
        return True

    dec = user_passes_test(check_login)
    return dec(func) 
Example #4
Source File: reports.py    From registrasion with Apache License 2.0 6 votes vote down vote up
def report_view(title, form_type=None):
    ''' Decorator that converts a report view function into something that
    displays a Report.

    Arguments:
        title (str):
            The title of the report.
        form_type (Optional[forms.Form]):
            A form class that can make this report display things. If not
            supplied, no form will be displayed.

    '''

    # Create & return view
    def _report(view):
        report_view = ReportView(view, title, form_type)
        report_view = user_passes_test(views._staff_only)(report_view)
        report_view = wraps(view)(report_view)

        # Add this report to the list of reports.
        _all_report_views.append(report_view)

        return report_view

    return _report 
Example #5
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 #6
Source File: decorators.py    From python with Apache License 2.0 5 votes vote down vote up
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                          login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator 
Example #7
Source File: decorators.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                          login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator 
Example #8
Source File: decorators.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                          login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator 
Example #9
Source File: decorators.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def user_is_project_admin(view_func):
    """Projet admin view decorator.

    Checks that the user is an admin, moderator or initiator of any project.
    """
    return user_passes_test(
        _user_is_project_admin,
    )(view_func) 
Example #10
Source File: decorators.py    From python2017 with MIT License 5 votes vote down vote up
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                          login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator 
Example #11
Source File: mixins.py    From registration with MIT License 5 votes vote down vote up
def is_organizer(f, raise_exception=True):
    """
    Decorator for views that checks whether a user is an organizer or not
    """

    def check_perms(user):
        if user.is_authenticated and user.email_verified and user.is_organizer and user.has_usable_password():
            return True
        # In case the 403 handler should be called raise the exception
        if raise_exception:
            raise PermissionDenied
        # As the last resort, show the login form
        return False

    return user_passes_test(check_perms)(f) 
Example #12
Source File: mixins.py    From registration with MIT License 5 votes vote down vote up
def is_hacker(f, raise_exception=True):
    """
    Decorator for views that checks whether a user is a hacker or not
    """

    def check_perms(user):
        if user.is_authenticated and user.email_verified and user.has_usable_password():
            return True
        # In case the 403 handler should be called raise the exception
        if raise_exception:
            raise PermissionDenied
        # As the last resort, show the login form
        return False

    return user_passes_test(check_perms)(f) 
Example #13
Source File: decorators.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def superuser_decorator(fn):
    check = user_passes_test(lambda user: user.is_superuser)
    return check(fn) 
Example #14
Source File: decorators.py    From elearning with MIT License 5 votes vote down vote up
def student_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    '''
    Decorator for views that checks that the logged in user is a student,
    redirects to the log-in page if necessary.
    '''
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_student,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #15
Source File: decorators.py    From elearning with MIT License 5 votes vote down vote up
def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    '''
    Decorator for views that checks that the logged in user is a teacher,
    redirects to the log-in page if necessary.
    '''
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_teacher,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #16
Source File: urls.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def adminurl(regexp, view, *args, **kwargs):
    view = user_passes_test(lambda u: u.is_superuser)(view)
    return url(regexp, view, *args, **kwargs)


# Anonymous views. 
Example #17
Source File: extension.py    From django-bananas with MIT License 5 votes vote down vote up
def admin_view(self, view, perm=None):
        if perm is not None:
            perm = self.get_permission(perm)
        else:
            perm = self.access_permission

        admin_login_url = compat.reverse_lazy("admin:login")
        view = user_passes_test(
            lambda u: u.is_active and u.is_staff, login_url=admin_login_url
        )(view)
        view = permission_required(perm, login_url=admin_login_url)(view)
        return view 
Example #18
Source File: decorators.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def account_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """Require that the (1) the user is logged in, or (2) that an account is not required to view the page.

    If the user fails the test, redirect the user to the log-in page. See also
    django.contrib.auth.decorators.login_required
    """
    req = getattr(settings, 'ACCOUNT_REQUIRED', False)
    actual_decorator = user_passes_test(
        lambda u: not req or u.is_authenticated,
        login_url=login_url,
        redirect_field_name=redirect_field_name,
    )
    if func:
        return actual_decorator(func)
    return actual_decorator 
Example #19
Source File: decorators.py    From interop with Apache License 2.0 5 votes vote down vote up
def require_superuser(func):
    """Decorator to check that user is a superuser before allowing view.

    Raises:
        PermissionDenied: User is not a superuser.
    """
    def check_superuser(user):
        if not user.is_superuser:
            raise PermissionDenied('Only superusers allowed.')
        return True

    dec = user_passes_test(check_superuser)
    return dec(func) 
Example #20
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def provider_required(func):
    return user_passes_test(provider_exists, login_url=reverse_lazy('new-provider'))(func) 
Example #21
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def provider_update_required(func):
    return user_passes_test(provider_has_updated, login_url=reverse_lazy('provider-update'))(func) 
Example #22
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def session_passes_test(test_func, fail_url,
                        redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the session passes the given test,
    redirecting to the choice page if necessary. The test should be a callable
    that takes the session object and returns True if the session passes. It's
    nearly a carbon copy of django.contrib.auth.decorators.user_passes_test.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.session):
                return view_func(request, *args, **kwargs)

            path = request.build_absolute_uri()
            resolved_url = resolve_url(fail_url)

            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.

            scheme, netloc = urlparse(resolved_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not scheme or scheme == current_scheme) and
                    (not netloc or netloc == current_netloc)):
                path = request.get_full_path()

            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_url, redirect_field_name)

        return _wrapped_view
    return decorator 
Example #23
Source File: decorators.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def instance_manager_required(function=None, redirect_to=None, raise_exception=False):
    """
    View decorator that checks whether the user is an InstanceManager, i.e.
      has the permission to browse their own instances or all instances.

    Modeled on django.contrib.auth.decorators.permission_required().

    :param function: view function to wrap
    :param redirect_to: URL to redirect to if user is not an InstanceManager user
    :param raise_exception: if set, will raise PermissionDenied if user is not an InstanceManager user.
    """
    def check_perm(user):
        """Checks if the user is an instance manager"""
        if InstanceReference.can_manage(user):
            return True
        # In case the 403 handler should be called raise the exception
        if raise_exception:
            raise PermissionDenied
        # Or, show login form.
        return False

    # Use the user_passes_test view decorator to handle redirect.
    actual_decorator = user_passes_test(
        check_perm,
        login_url=redirect_to,
        redirect_field_name=None
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #24
Source File: decorators.py    From django-multiple-user-types-example with MIT License 5 votes vote down vote up
def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    '''
    Decorator for views that checks that the logged in user is a teacher,
    redirects to the log-in page if necessary.
    '''
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_teacher,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #25
Source File: decorators.py    From django-multiple-user-types-example with MIT License 5 votes vote down vote up
def student_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    '''
    Decorator for views that checks that the logged in user is a student,
    redirects to the log-in page if necessary.
    '''
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_student,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #26
Source File: decorator.py    From zulip with Apache License 2.0 5 votes vote down vote up
def zulip_otp_required(
    redirect_field_name: str='next',
    login_url: str=settings.HOME_NOT_LOGGED_IN,
) -> Callable[[ViewFuncT], ViewFuncT]:
    """
    The reason we need to create this function is that the stock
    otp_required decorator doesn't play well with tests. We cannot
    enable/disable if_configured parameter during tests since the decorator
    retains its value due to closure.

    Similar to :func:`~django.contrib.auth.decorators.login_required`, but
    requires the user to be :term:`verified`. By default, this redirects users
    to :setting:`OTP_LOGIN_URL`.
    """

    def test(user: UserProfile) -> bool:
        """
        :if_configured: If ``True``, an authenticated user with no confirmed
        OTP devices will be allowed. Default is ``False``. If ``False``,
        2FA will not do any authentication.
        """
        if_configured = settings.TWO_FACTOR_AUTHENTICATION_ENABLED
        if not if_configured:
            return True

        return user.is_verified() or (user.is_authenticated
                                      and not user_has_device(user))

    decorator = django_user_passes_test(test,
                                        login_url=login_url,
                                        redirect_field_name=redirect_field_name)

    return decorator 
Example #27
Source File: ajax.py    From dissemin with GNU Affero General Public License v3.0 5 votes vote down vote up
def deleteResearcher(request, pk):
    """
    Deletes a researcher (from a department). Their papers are
    left as they are.
    """
    researcher = get_object_or_404(Researcher, pk=pk)
    dept = researcher.department
    researcher.delete()
    if dept:
        dept.update_stats()
    return HttpResponse('OK', content_type='text/plain')

# paper management
#@user_passes_test(is_admin)
# def changepaper(request):
#    allowedFields = ['title']
#    return process_ajax_change(request, Paper, allowedFields)

# department management
#@user_passes_test(is_admin)
# def changedepartment(request):
#    allowedFields = ['name']
#    return process_ajax_change(request, Department, allowedFields)

# researcher management
#@user_passes_test(is_admin)
# def changeresearcher(request):
#    allowedFields = ['role']
#    return process_ajax_change(request, Researcher, allowedFields) 
Example #28
Source File: decorators.py    From fermentrack with MIT License 5 votes vote down vote up
def login_if_required_for_dashboard(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary -
    but only if REQUIRE_LOGIN_FOR_DASHBOARD is set True in Constance.
    """

    def authenticated_test(u):
        if config.REQUIRE_LOGIN_FOR_DASHBOARD:
            return u.is_authenticated
        else:
            return True

    actual_decorator = user_passes_test(
        authenticated_test,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator 
Example #29
Source File: decorators.py    From bioforum with MIT License 5 votes vote down vote up
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                          login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator 
Example #30
Source File: decorators.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )(view_func)