Le mercredi 17 janvier 2007 à 11:06 +0100, FB a écrit :
> Hi,
> 
> On Tue, Jan 16, 2007 at 01:15:53PM -0500, Stephan Richter wrote:
> > On Tuesday 16 January 2007 12:39, FB wrote:
> > > is there a way to get all the permissions and roles, the current principal
> > > is associated to for a given object?
> > >
> > > Something like:
> > >
> > >  getAllRoles(context)
> > >  getAllPermissions(context)
> > 
> > No. You would have to write your own code doing that. Note that it really 
> > depends on the security policy on what roles and permissions are available.
> 
> My securitypolicy is z.a.securitypolicy :-) .

Hi,

I've written my own adapter to get the list of roles granted or denied
for a given principal, and the list of principals granted or denied for
a given role, always in the context of the adapted object ; you'll find
the source code into joined files, just having to configure it :

            <adapter
                factory=".manager.SecurityManager"
                provides=".interfaces.ISecurityManager"
                for="zope.annotation.interfaces.IAnnotatable"
                trusted="true" />
        
            <class class=".manager.SecurityManager">
                <allow
                    interface=".interfaces.ISecurityManager" />
            </class>
        
I'm far from sure if this is the best approach, but at list it works for
my own needs in the context of zope.app.securitypolicy.
Writing the same adapter to get the list of permissions (by iterating
throught the list of granted or denied roles and using the
IRolePermissionManager interface) shouldn't be too difficult...

Hope this will help you,

  Thierry Florac
-- 
  Chef de projet intranet/internet
  Office National des Forêts - Département Informatique
  2, Avenue de Saint-Mandé
  75570 PARIS Cedex 12
  Mél : [EMAIL PROTECTED]
  Tél. : +33 01.40.19.59.64
  Fax. : +33 01.40.19.59.85
# Copyright (C) ONF 2006 by Thierry Florac


"""
"""

__version__   = "$Revision: $"
__release__   = "$Id: $"
__docformat__ = 'restructuredtext'


# import Zope3 interfaces
from zope.interface import Interface

# import local interfaces

# import Zope3 packages

# import local packages

from ulthar import _


class ISecurityManager(Interface):
    """This facility class is used to access roles and permissions on a given object for current interaction"""

    def getLocalRoles(principal=None):
        """Get principal allowed and denied roles on current object

        Result is given as a dictionary :
        { 'allow': ['role1','role2'], 'deny': ['role3',] }
        """

    def getLocalAllowedRoles(principal=None):
        """Get list of locally allowed roles"""

    def getLocalDeniedRoles(principal=None):
        """Get list of locally denied roles"""

    def getRoles(principal=None):
        """Get list of roles, including inherited ones
        
        Result is given as a dictionary :
        { 'allow': ['role1','role2'], 'deny': ['role3',] }
        """
        
    def getAllowedRoles(principal=None):
        """Get list of allowed roles, including inherited ones"""

    def getDeniedRoles(principal=None):
        """Get list of denied roles, including inherited ones"""

    def getLocalPrincipals(roleId):
        """Get list of principals with locally defined role
        
        Result is given as a dictionary :
        { 'allow': ['principal1','principal2'], 'deny': ['principal3',] }
        """

    def getLocalAllowedPrincipals(roleId):
        """Get list of principals with locally granted role"""
        
    def getLocalDeniedPrincipals(roleId):
        """Get list of principals with locally denied role"""

    def getPrincipals(roleId):
        """Get list of principals with access defined for allowed role, including inherited ones
        
        Result is given as a dictionary :
        { 'allow': ['principal1','principal2'], 'deny': ['principal3',] }
        """

    def getAllowedPrincipals(roleId):
        """Get list of principals with granted access to specified role, including inherited ones"""

    def getDeniedPrincipals(roleId):
        """Get list of principals with denied access to specified role, including inherited ones"""

    def canUseRole(roleId, principal=None):
        """Return true or false to specify role usage for given principal"""

    def canUsePermission(permission, principal=None):
        """Return true or false to specify permission usage for given principal"""

    def canView(principal=None):
        """Return true or false if 'zope.View' permission is granted to given principal"""
# Copyright (C) ONF 2006 by Thierry Florac


"""
"""

__version__   = "$Revision: $"
__release__   = "$Id: $"
__docformat__ = 'restructuredtext'


# import Zope3 interfaces
from zope.interface import implements
from zope.publisher.interfaces import IRequest
from zope.security.interfaces import IPrincipal
from zope.app.securitypolicy.interfaces import IPrincipalRoleManager

# import local interfaces
from interfaces import ISecurityManager

# import Zope3 packages
from zope.app import zapi
from zope.security.management import checkPermission, getInteraction

# import local packages

from ulthar import _


class SecurityManager(object):
    
    implements(ISecurityManager)

    def __init__(self, context, request=None):
        self.context,self.request = context,request

    def getRequest(self):
        interaction = getInteraction()
        for participation in interaction.participations:
            if IRequest.providedBy(participation):
                return participation
        raise RuntimeError(_("No IRequest in interaction"))
        
    def getPrincipal(self):
        """Extract principal from current interaction"""
        if self.request is None:
            self.request = self.getRequest()
        return self.request.principal

    def getLocalRoles(self, principal=None):
        if principal is None:
            principal = self.getPrincipal()
        if not principal:
            return None
        if type(principal) in (str,unicode):
            id = principal
        else:
            id = principal.id
        manager = IPrincipalRoleManager(self.context)
        roles = manager.getRolesForPrincipal(id)
        return { 'allow': [ role[0] for role in roles if role[1].getName() == 'Allow' ],
                 'deny':  [ role[0] for role in roles if role[1].getName() == 'Deny' ] }

    def getLocalAllowedRoles(self, principal=None):
        return self.getLocalRoles(principal)['allow']

    def getLocalDeniedRoles(self, principal=None):
        return self.getLocalRoles(principal)['deny']

    def getRoles(self, principal=None):
        result = { 'allow': [],  'deny': [] }
        context = self.context
        while context is not None:
            roles = ISecurityManager(context).getLocalRoles(principal)
            for role in roles['allow']:
                if (role not in result['deny']) and (role not in result['allow']):
                    result['allow'].append(role)
            for role in roles['deny']:
                if (role not in result['allow']) and (role not in result['deny']):
                    result['deny'].append(role)
            context = zapi.getParent(context)
        return result

    def getAllowedRoles(self, principal=None):
        return self.getRoles(principal)['allow']

    def getDeniedRoles(self, principal=None):
        return self.getRoles(principal)['deny']

    def getLocalPrincipals(self, roleId):
        manager = IPrincipalRoleManager(self.context)
        principals = manager.getPrincipalsForRole(roleId)
        return { 'allow': [ principal[0] for principal in principals if principal[1].getName() == 'Allow' ],
                 'deny':  [ principal[0] for principal in principals if principal[1].getName() == 'Deny' ] }

    def getLocalAllowedPrincipals(self, roleId):
        return self.getLocalPrincipals(roleId)['allow']

    def getLocalDeniedPrincipals(self, roleId):
        return self.getLocalPrincipals(roleId)['deny']

    def getPrincipals(self, roleId):
        result = { 'allow': [], 'deny': [] }
        context = self.context
        while context is not None:
            principals = ISecurityManager(context).getLocalPrincipals(roleId)
            for principal in principals['allow']:
                if (principal not in result['deny']) and (principal not in result['allow']):
                    result['allow'].append(principal)
            for principal in principals['deny']:
                if (principal not in result['allow']) and (principal not in result['deny']):
                    result['deny'].append(principal)
            context = zapi.getParent(context)
        return result
        
    def getAllowedPrincipals(self, roleId):
        return self.getPrincipals(roleId)['allow']

    def getDeniedPrincipals(self, roleId):
        return self.getPrincipals(roleId)['deny']

    def canUseRole(self, roleId, principal=None):
        if principal is None:
            principal = self.getPrincipal()
            if IPrincipal.providedBy(principal) and (principal.id == 'zope.manager'):
                return True
        return roleId in ISecurityManager(self.context).getAllowedRoles(principal)

    def canUsePermission(self, permission):
        try:
            return checkPermission(permission, self.context)
        except:
            return False

    def canView(self):
        return self.canUsePermission('zope.View')
_______________________________________________
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users

Reply via email to