quick search:
 

Checking the rights of a User to access and object

Submitted by: Cheez
Last Edited: 2004-10-14

Category: Python(Script)

Average rating is: 5.0 out of 5 (2 ratings)

Description:
given an object, find out if a user has the rights to access the object, in their current context.

Source (Text):
try:
    object= getattr(context,link)
    if not object.acquiredRolesAreUsedBy( permission ):
        for p in object.rolesOfPermission( permission ):
                 if p['selected']:
                     if p['name'] in user.getRoles():
                       return 1
    else:
       return 1
except:
    pass
return 0

Explanation:
This script needs to be in a script given a management role .

object is the object in the context you want to check it in.
permission is the permission you want to check typically ('View')

it first checks to see if it acquires the role from its parent. If it does I assume (possible incorrectly) it can be accessed. If you wanted to be more accurate, you could recurse until you hit the a parent that didn't acquire, and check that.

Then it checks the rolesOfPermission for the object and role your looking for. This returns a dictionary , where name is the name of the role, and selected evaluates to true if that role has the permission for that object. This is used by the Security tab in the ZMI to populate the checkboxes.

If the user has a role that has the permission you want it returns true.

If it has no matches, or runs into a exception it returns false.


Thanks to philiKON for helping my clean this up from my original



Comments:

return values by alfons - 2004-10-14
'selected' evaluates to 'SELECTED' or '' (and not, as you stated, to true)


How to check access with localroles by billpage - 2004-10-14
# The following script collects email addresses of those users
# who have 'View' access to an obect. I use it in a Notify workflow
contentObject = state_change.object
mailList=[]
for thisMember in context.portal_membership.listMembers():
    if thisMember.listed and thisMember.email:
        try:
            if not contentObject.acquiredRolesAreUsedBy( 'View' ):
                for p in contentObject.rolesOfPermission( 'View' ):
                     if p['selected']:
                         if p['name'] in thisMember.getRolesInContext(contentObject):
                             mailList.append(thisMember.email)
            else:
               mailList.append(thisMember.email)
        except:
            pass