In my Grok application I have a container of objects and I'd like to limit the objects that a particular principal can view based on an attribute of the principal and the object. If the principal is an administrator they're able to view any of the objects.
I've got this to work by using a Traverser that raises an Unauthorized exception if the attributes don't match up, but I was wondering if there was a better way to handle this.
# simplified slightly...
class MyObjectTraverser(grok.Traverser):
grok.context(MyContainer)
def traverse(self, name):
# If the logged in user is an administrator, return the object
if principal.isAdmin():
return context[name]
# Otherwise check that the principal and object match up
if principal.client_id == context[name].client_id:
return context[name]
# Deny access to the object
raise Unauthorized
Is there a more Zope-style way of doing this that wouldn't be difficult to manage? One thing I do like about this approach is that if I wanted to further limit access to the objects in the container it would be relatively straightforward to do so.
# Otherwise check that the principal and object match up and that it's orange
if principal.client_id == context[name].client_id and context[name].isOrange():
return context[name]