0

In my Django project, I want to restrict a page depending on if they have an access level of 100, 200, etc. I tried making a wrapper for this like login_required, however I'm not sure how to access the user model. Any advice?

Example:

def required_access(access):
    if access <= user.access:
        print 'The user can access this page, their access level is greater than or equal to whats required.'
    else:
        print 'This page cannot be viewed, their access level is too low.'

@login_required
@required_access(300)
def foo(request):
    return render(request, 'bar.html', {})
Magic
  • 362
  • 1
  • 4
  • 13

2 Answers2

1

Python decorators have access to the wrapped functions arguments.

With this knowledge we could alter our decorator like so, to have access to the request.user object. This is assuming the first argument to my_view() will always be the request object.

def required_access(access=None):
    def wrap(func):
        def inner(*args, **kwargs):
            if access <= args[0].user.access:
                print 'The user can access this page, their access level is greater than or equal to whats required.'
            else:
                print 'This page cannot be viewed, their access level is too low.'
            return func(*args, **kwargs)
        return inner
    return wrap

@login_required
@required_access(access=300)
def foo(request):
    return render(request, 'bar.html', {})
Kevin Cherepski
  • 1,473
  • 8
  • 8
0

Try this..

https://docs.djangoproject.com/en/1.7/topics/auth/default/#limiting-access-to-logged-in-users-that-pass-a-test

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.email.endswith('@example.com')

@user_passes_test(email_check)
def my_view(request):
    [...]
mishbah
  • 5,487
  • 5
  • 25
  • 35
  • I tried doing something like this, but how can I return something such as `if access <= user.access:` ? – Magic Mar 02 '15 at 23:16