Login

View Permission Decorator Helper

Author:
jgeewax
Posted:
July 4, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

gamaroff (on June 14, 2012):

Cool snippet. Thanks!

#

Please login first before commenting.