Check permission by role instead of user?

What is the best way to check for a permission on a context by role instead of by user/username? For instance, to see if the Anonymous role is granted access to the 'View' permission. The best I could find was the following, which seems like it's probably missing some better exposed API

name, value = [perm[:2] for perm in obj.ac_inherited_permissions(1) if perm[0] == 'View'][0]
p = Permission(name, value, obj)
anon_view = 'Anonymous' in p.getRoles(default=[])

For context, a feature request is to indicate to an editor somehow that internal links within a Page point to objects that are in a workflow state that the user can't see.

Normally one would just the check permission using the following:

from AccessControl import getSecurityManager
sm = getSecurityManager()
sm.checkPermission('Some permission', someObject)

But if you need to show an overview of roles for permissions, then this should work: https://stackoverflow.com/questions/13426188/zope-getting-acquired-permission-of-a-role-on-object.

from AccessControl.PermissionRole import rolesForPermissionOn

roles = rolesForPermissionOn(permission, context)

The you can do

'role name' in roles
1 Like

checkPermission works on the current user no? rolesforPermissionOn looks like what I want, thanks!