How do I query the role(s) of the current user?

To get the Roles that have been granted to a user for a particular object:

from zope.app.securitypolicy.interfaces import IGrantInfo
grant_info = IGrantInfo(obj) # your object of interest
print grant_info.getRolesForPrincipal('your.principal.id')

If you are protecting Views with Permissions, then granting Permissions to Roles, and finally Roles to Principals, you can programmatically inspect this information with the following sample code:

from zope.app.securitypolicy.interfaces import IRolePermissionManager
from zope.app.securitypolicy.interfaces import IPrincipalRoleManager
from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager

obj = self.context # adjust this to get the object that your are interested in

role_permission = IRolePermissionManager(obj, None)
principal_role = IPrincipalRoleManager(obj, None)
principal_permission = IPrincipalPermissionManager(obj, None)

print "Roles to Permissions map: %s" % role_permissions.getRolesAndPermissions()
print "Principal to Roles map: %s" % principal_role.getPrincipalsAndRoles()
print "Principal to Permissions map: %s" %  principal_permission.getPrincipalsAndPermissions()

This will only get the immediate security mappings for an object. In a typical situation you may have a container for your application that provides the ISite? interface. This site object is where you would store your particular security maps. In a more complex use case, you may have a tree of objects, with certain permissions on granted further down the tree. In this case given an object that is further down the tree, you would need to walk back up the tree, inspecting permissions at each step. Walking back up the tree of an object is as simple as:

while ob is not None:
    # fetch some security information here ...
    # then set the current ob to it's parent container
    # the loop will break when we try and walk above the root
    ob = getattr(ob, '__parent__', None)

Finally, there is a convience function in the default Zope 3 security policy called settingsForObject that will gather and display all grants that have been given to a particular object. This can be called on any object:

from zope.app.securitypolicy.zopepolicy import settingsForObject
print settingsForObject( someObjectOfInterest )

The source code for this function is also quite instructional in how to query for security information in Zope 3.

There is also an instructive E-mail by Thierry Florac at: http://www.mail-archive.com/zope3-users@zope.org/msg04893.html



( 96 subscribers )