Login

View Permission Decorator Helper

Author:
jgeewax
Posted:
July 4, 2008
Language:
Python
Version:
.96
Tags:
view decorator permission
Score:
1 (after 1 ratings)

This is a simple helper to make custom permission decorators for Django views.

Perhaps you have an edit_comment view which you want to make sure current user is the owner of:

def edit_comment(request, comment_id):

if request.user == Comment(id=comment_id).user:

... do authorized things ...

else:

... do unauthorized things ...

... ...

In this view, you might do a quick check if request.user == Comment(id=comment_id).user, however you now need to duplicate this code all over the place whenever you want to check if a comment is owned by the current user.

Instead, you can use the built in login_required decorator, and your own decorator to do the test:

@permission

def user_owns_comment(request, comment_id):

return request.user == Comment(id=comment_id)

@login_required

@user_owns_comment

def edit(request, comment_id):

... ... ...

The "tester" function will post a message using the messages module built into Django, and redirect the user to the root. It allows access and executes the view if the tester function returns anything that evaluates to True.

Your permission tester should either strictly specify the same arguments as the view, or take additional args, and *kwargs to prevent syntax errors on extra arguments being passed along.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.http import HttpResponseRedirect
from functools import wraps

def permission(permission_tester):
    @wraps(permission_tester)
    def view_decorator(view_function):
        @wraps(view_decorator)
        def decorated_view(request, *args, **kwargs):
            if permission_tester(request, *args, **kwargs):
                view_result = view_function(request, *args, **kwargs)
            else:
                try:
                    request.user.message_set.create(message="Sorry, you don't have the necessary permissions to view that page.")
                except: pass
                view_result = HttpResponseRedirect("/")
            return view_result
        return decorated_view
    return view_decorator

More like this

  1. FieldLevelPermissionsAdmin by buriy 7 years, 9 months ago
  2. JSON decorator for views handling ajax requests by anilshanbhag 2 years, 6 months ago
  3. Allow separation of GET and POST implementations by agore 3 years ago
  4. dropbox integration by ivarne 3 years, 3 months ago
  5. Cache view by user (and anonymous) by rafaelsdm 3 years, 10 months ago

Comments

gamaroff (on June 14, 2012):

Cool snippet. Thanks!

#

Please login first before commenting.