Checking PermissionsΒΆ
How to check permission in python code.
When generating user interface elements you might want to check that the current logged in principal actually can access a view to which a link refers. You need to do two things: 1 get the view, 2 check permissions on that view. This is how you do it:
from zope.component import getMultiAdapter
from zope.security import canAccess
def canAccessView(obj, view_name):
# obj - is the object you want view
# view_name - is the grok.View/AddForm/EditForm you want to access
view = getMultiAdapter((obj, self.request), name=view_name)
# check if you can access the __call__ method which is equal
# to being allowed to access this view.
return canAccess(view, '__call__')
If you want to check if the current logged in principal has a specific permission on a specific object or view you can do so by means of the checkPermission method. It is available through zope.security and in a view through self.request.interaction. Note that Grok doesn’t allow a simplified way of setting object level permissions. The grok.requires statement is only applicable to views.
from zope.security import checkPermission
def justChecking(context):
# context - the object or view you are checking permissions on
user_allowed = checkPermission(PERMISSION_NAME, context)
class MyView(grok.View):
def update(self):
i = self.request.interaction
# checking permission on currently viewed object (self.context)
user_allowed = i.checkPermission(PERMISSION_NAME, self.context)