tags:

views:

268

answers:

2

For my site I created an abstract Model which implements model-level read permissions. That part of the system is completed and works correctly. One of the methods the permissioned model exposes is is_safe(user) which can manually test if a user is allowed to view that model or not.

What I would like to do is add a method to the effect of continue_if_safe which can be called on any model instance, and instead of returning a boolean value like is_safe it would first test if the model can be viewed or not, then in the case of False, it would redirect the user, either to the login page if they aren't already logged in or return a 403 error if they are logged in.

Ideal usage:

model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
# ... remainder of code to be run if it's safe down here ...

I peeked at how the get_object_or_404 works, and it throws an Http404 error which seems to make sense. However, the problem is that there don't seem to be equivalent redirect or 403 errors. What's the best way to go about this?

(non-working) continue_if_safe method:

def continue_if_safe(self, user):

    if not self.is_safe(user):
        if user.is_authenticated():
            raise HttpResponseForbidden()
        else:
            raise HttpResponseRedirect('/account/')

    return

Edit -- The Solution

The code for the final solution, in case other "stackers" need some help with this:

In the Abstract Model:

def continue_if_safe(self, user):
    if not self.is_safe(user):
        raise PermissionDenied()
    return

Views are caught by the middleware:

class PermissionDeniedToLoginMiddleware(object):
    def process_exception(self, request, exception):
        if type(exception) == PermissionDenied:
            if not request.user.is_authenticated():
                return HttpResponseRedirect('/account/?next=' + request.path)
        return None

Usage in the view (very short and sweet):

model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
+2  A: 

For the forbidden (403) error, you could raise a PermissionDenied exception (from django.core.exceptions).

For the redirecting behaviour, there's no built-in way to deal with it the way you describe in your question. You could write a custom middleware that will catch your exception and redirect in process_exception.

Clément
Between the time I first read your answer and when you edited it I did just what you recommended (in your edit). It seems to be working great.
T. Stone
+1  A: 

You want to use decorators for this. Look up login_required for an example. Basically the decorator will allow you check check the safety and then return HttpResponseRedirect() if its not safe.

Your code will end up looking something like this:

@safety_check:
def some_view(request):
    #Do Stuff
Zach
But the safety check is relative to the *query* not the *user*, which makes this pattern rather difficult, don't you think? It's not a matter of if the user has permission to see the view, it's a matter of which records within the view they have access to.
T. Stone
You would be able to do that check in the decorator function.
Zach