[Checkins] SVN: z3c.securitytool/trunk/src/z3c/securitytool/ Misc Refactoring and code cleanup

Daniel Blackburn blackburnd at gmail.com
Wed Feb 20 12:28:59 EST 2008


Log message for revision 84082:
  Misc Refactoring and code cleanup

Changed:
  U   z3c.securitytool/trunk/src/z3c/securitytool/README.txt
  U   z3c.securitytool/trunk/src/z3c/securitytool/browser/configure.zcml
  U   z3c.securitytool/trunk/src/z3c/securitytool/configure.zcml
  U   z3c.securitytool/trunk/src/z3c/securitytool/securitytool.py

-=-
Modified: z3c.securitytool/trunk/src/z3c/securitytool/README.txt
===================================================================
--- z3c.securitytool/trunk/src/z3c/securitytool/README.txt	2008-02-20 17:28:29 UTC (rev 84081)
+++ z3c.securitytool/trunk/src/z3c/securitytool/README.txt	2008-02-20 17:28:58 UTC (rev 84082)
@@ -225,7 +225,9 @@
 roles, permissions and groups.
 
     >>> from z3c.securitytool.interfaces import ISecurityChecker
+    >>> from z3c.securitytool.securitytool import PrincipalDetails
     >>> principals = zapi.principals()
+
     >>> first = ISecurityChecker(firstIssue)
 
 
@@ -379,7 +381,8 @@
     ...             'principalRoles'      : [prinRoleMap]}
 
 
-    >>> first._permissionDetails(daniel, 'takeOverTheWORLD',
+    >>> permDetails = PermissionDetails(firstIssue)
+    >>> permDetails.permissionDetails(daniel, 'takeOverTheWORLD',
     ...                          [['viewName',settings]],[rolePermMap])
     {'groups': {},
      'roles': {'Janitor': [{'setting': 'Allow', 'name': 'viewName'}]},
@@ -387,8 +390,9 @@
 
 
 Here we will test with the principal that was populated earlier.
+    >>> prinDetails = PrincipalDetails(firstIssue)
     >>> daniel  = principals.definePrincipal('daniel','daniel','daniel')
-    >>> pprint(first.principalPermissions('daniel') )
+    >>> pprint(prinDetails.principalPermissions('daniel') )
     {'groups': {},
      'permissionTree': [],
      'permissions': [],
@@ -402,7 +406,7 @@
 
 
 
-    >>> print first.permissionDetails('daniel', None)
+    print permDetails('daniel', None, firstIssue)
     {'read_perm': 'zope.Public',
      'groups': {},
      'roles': [],
@@ -414,7 +418,7 @@
 
     >>> from zope.testbrowser.testing import Browser
     >>> manager = Browser()
-    >>> authHeader = 'Basic mgr:mgrpw'
+    >>> authHeader = 'Basic admin:admin'
     >>> manager.addHeader('Authorization', authHeader)
     >>> manager.handleErrors = False
 

Modified: z3c.securitytool/trunk/src/z3c/securitytool/browser/configure.zcml
===================================================================
--- z3c.securitytool/trunk/src/z3c/securitytool/browser/configure.zcml	2008-02-20 17:28:29 UTC (rev 84081)
+++ z3c.securitytool/trunk/src/z3c/securitytool/browser/configure.zcml	2008-02-20 17:28:58 UTC (rev 84082)
@@ -5,19 +5,19 @@
 
   <page name="securityMatrix.html"
       for="*"
-      class=".views.ViewPrincipalMatrix"
+      class=".views.PrincipalMatrixView"
       permission="zope.Public"
   />
 
   <page name="principalDetails.html"
       for="*"
-      class=".views.PrincipalDetails"
+      class=".views.PrincipalDetailsView"
       permission="zope.Public"
   />
 
   <page name="permissionDetails.html"
       for="*"
-      class=".views.PermissionDetails"
+      class=".views.PermissionDetailsView"
       permission="zope.Public"
   />
 

Modified: z3c.securitytool/trunk/src/z3c/securitytool/configure.zcml
===================================================================
--- z3c.securitytool/trunk/src/z3c/securitytool/configure.zcml	2008-02-20 17:28:29 UTC (rev 84081)
+++ z3c.securitytool/trunk/src/z3c/securitytool/configure.zcml	2008-02-20 17:28:58 UTC (rev 84082)
@@ -2,18 +2,22 @@
     xmlns="http://namespaces.zope.org/zope"
     >
 
-    <!--adapter Test Adapter
+  <adapter
       factory=".securitytool.SecurityChecker"
-      provides="z3c.securitytool.interfaces.ISecurityChecker"
-      name="securityToolChecker"
-      permission="zope.Public"
-    /-->
+      for="*"
+      />
 
   <adapter
-      factory=".securitytool.SecurityChecker"
+      factory=".securitytool.PermissionDetails"
       for="*"
       />
 
+  <adapter
+      factory=".securitytool.PrincipalDetails"
+      for="*"
+
+      />
+
   <include package=".browser" />    
 
 

Modified: z3c.securitytool/trunk/src/z3c/securitytool/securitytool.py
===================================================================
--- z3c.securitytool/trunk/src/z3c/securitytool/securitytool.py	2008-02-20 17:28:29 UTC (rev 84081)
+++ z3c.securitytool/trunk/src/z3c/securitytool/securitytool.py	2008-02-20 17:28:58 UTC (rev 84082)
@@ -14,6 +14,8 @@
 from zope.securitypolicy.principalrole import principalRoleManager
 from zope.securitypolicy.rolepermission import rolePermissionManager
 
+from zope.app.container.interfaces import IContainer
+
 from z3c.securitytool import interfaces
 
 class SecurityChecker(object):
@@ -24,19 +26,6 @@
     def __init__(self, context):
         self.context = context
 
-    def getView(self, view_reg, skin=IBrowserRequest):
-        """Instantiate view from given registration and skin.
-           Return `None` if the view isn't callable.
-        """
-        request = TestRequest()
-        applySkin(request, skin)
-        try:
-            view_inst = view_reg.factory(self.context, request)
-            if callable(view_inst):
-                return view_inst
-        except TypeError:
-            pass
-
     def getPermissionSettingsForAllViews(self,interfaces,
                                          skin=IBrowserRequest,
                                          selectedPermission=None):
@@ -55,7 +44,7 @@
 
         for iface in interfaces:
             for view_reg in getViews(iface, self.skin):
-                viewInstance = self.getView(view_reg, self.skin)
+                viewInstance = getView(self.context, view_reg, self.skin)
                 if viewInstance:
                     self.populateMatrix(viewInstance,view_reg)
 
@@ -80,14 +69,14 @@
                 val = self.viewRoleMatrix[item][viewSetting] \
                                                and 'Allow' or '--'
                 self.viewMatrix[item].update({viewSetting:val})
-        
+
         for item in self.viewPermMatrix:
             if not  self.viewMatrix.has_key(item):
                 self.viewMatrix[item] = {}
             for viewSetting in self.viewPermMatrix[item]:
                 self.viewMatrix[item].update(
                       {viewSetting:self.viewPermMatrix[item][viewSetting]})
-    
+
     def getReadPerm(self,view_reg):
         """ Helper method which returns read_perm and view name"""
         info = getViewInfoDictionary(view_reg)
@@ -108,7 +97,7 @@
             return
         self.views[self.name] = read_perm
 
-        allSettings, settings = self.getSettingsForMatrix(viewInstance)
+        allSettings, settings = getSettingsForMatrix(viewInstance)
         rolePermMap = allSettings.get('rolePermissions', ())
 
         for name,setting in settings:
@@ -153,28 +142,7 @@
                 self.viewRoleMatrix[principal][name] = {}
             self.viewRoleMatrix[principal][name].update({role:permSetting})
 
-    def getSettingsForMatrix(self,viewInstance):
-        """ Here we aggregate all the principal permissions into one object
-            We need them all for our lookups to work properly in
-            principalRoleProvidesPermission.
-        """
-        allSettings = {}
-        permSetting = ()
-        settingList = [val for name ,val  in settingsForObject(viewInstance)]
 
-        # The settings list is an aggregate of all settings
-        # so we can lookup permission settings for any role
-        for setting in settingList:
-            for key,val in setting.items():
-                if not allSettings.has_key(key):
-                    allSettings[key] = []
-                allSettings[key].extend(val)
-
-        settings= settingsForObject(viewInstance)
-        settings.reverse()
-
-        return allSettings, settings
-
     def populatePermissionMatrix(self,read_perm,principalPermissions):
         """ This method populates the principal permission section of
             the view matrix
@@ -194,6 +162,105 @@
                 else:
                     self.viewPermMatrix[principal] = {self.name: permSetting}
 
+class PermissionDetails(object):
+    implements(interfaces.IPermissionDetails)
+
+    #adapts(Interface,IBrowserRequest)
+
+    def __init__(self,context):
+        self.context = context
+
+    def __call__(self,principal_id,view_name,skin):
+        """Get permission details for a given principal and view.
+        Includes the permissions set by the groups the principal belongs to.
+        """
+
+        principals = zapi.principals()
+        principal = principals.getPrincipal(principal_id)
+        
+        settings = None
+        rolePermissions = []
+        read_perm = 'zope.Public'
+        prinPermSettings =  {'read_perm':'',
+                              'permissions': [],
+                              'roles': [],
+                              'groups': {}}
+
+        ifaces = tuple(providedBy(self.context))
+        for iface in ifaces:
+            for view_reg in getViews(iface, skin):
+                if view_reg.name == view_name:
+
+                    view = getView(self.context, view_reg, skin)
+                    settings = settingsForObject(view)
+                    read_perm = getViewInfoDictionary(view_reg)['read_perm'] or 'zope.Public'
+                    break
+
+        if settings:
+            for name,setting in settings:
+                if setting.get('rolePermissions',''):
+                    rolePermissions.extend(setting['rolePermissions'])
+
+            prinPermSettings = self.permissionDetails(principal,
+                                                       read_perm,
+                                                       settings,
+                                                       rolePermissions)
+
+        prinPermSettings['read_perm'] = read_perm
+
+        return prinPermSettings
+
+    def permissionDetails(self,principal,read_perm,settings, rolePermissions):
+        """Recursively get the permission details for a given principal and
+        permission from a security mapping.
+        """
+        principalSettings = {'permissions': [],
+                             'roles': {},
+                             'groups': {}}
+        principals = zapi.principals()
+
+        for name, setting in settings:
+            prinPermMap = setting.get('principalPermissions', ())
+            prinRoleMap = setting.get('principalRoles', ())
+            rolePermMap = rolePermissions
+            permSetting = principalDirectlyProvidesPermission(prinPermMap,
+                principal.id, read_perm)
+            if permSetting:
+                principalSettings['permissions'].append(
+                    {'name': renderedName(name), 'setting': permSetting})
+
+            role_id, permSetting = principalRoleProvidesPermission(
+                prinRoleMap, rolePermMap, principal.id,read_perm )
+            if permSetting:
+                nameList = principalSettings['roles'].setdefault(role_id, [])
+                nameList.append({'name': renderedName(name),
+                                 'setting': permSetting})
+
+            for group_id in principal.groups:
+                group = principals.getPrincipal(group_id)
+                group_settings = self.permissionDetails(group,
+                    read_perm, settings, rolePermMap)
+
+                if hasPermissionSetting(group_settings):
+                    principalSettings['groups'][group_id] = group_settings
+
+        return principalSettings
+
+class PrincipalDetails(object):
+    implements(interfaces.IPrincipalDetails)
+    adapts(Interface)
+
+
+    def __init__(self,context):
+        self.context = context
+        #self.secChecker = SecurityChecker(self.context)
+
+    def __call__(self,principal_id,view_name, skin=IBrowserRequest):
+        self.principal_id = principal_id
+        self.view_name = view_name
+        self.skin = skin
+
+
     def principalPermissions(self, principal_id, skin=IBrowserRequest):
         """Return all security settings (permissions, groups, roles)
            for all interfaces provided by this context for a
@@ -213,16 +280,15 @@
 
         for iface in ifaces:
             for view_reg in getViews(iface, IBrowserRequest):
-                view = self.getView(view_reg, skin)
+                view = getView(self.context, view_reg, skin)
                 if not view:
                     continue
                 all_settings = [{name:val} for name,val in
                                  settingsForObject(view) ]
 
-                self.roleSettings, junk = \
-                              self.getSettingsForMatrix(view)
+                self.roleSettings, junk = getSettingsForMatrix(view)
 
-                self.populatePrincipalMatrix(all_settings)
+                self.updatePrincipalMatrix(all_settings)
 
         self.orderRoleTree()
         return self.principalMatrix
@@ -230,27 +296,28 @@
     def orderRoleTree(self):
         # This is silly I know but I want global settings at the end
         try:
-            globalSettings = self.principalMatrix['roleTree'].pop(0)
-            self.principalMatrix['roleTree'].append(globalSettings)
+            roleTree = self.principalMatrix['roleTree']
+            globalSettings = roleTree.pop(0)
+            roleTree.append(globalSettings)
         except IndexError:
             # Attempting to pop empty list
             pass
 
-    def populatePrincipalMatrix(self, settings):
+    def updatePrincipalMatrix(self, settings):
         """ this method recursively populates the principal permissions
             dict and is only used by principalPermissions """
 
         for setting in settings:
             for name, item in setting.items():
-                self.populatePrincipalMatrixRoles(name,item)
-                self.populatePrincipalMatrixPermissions(item)
+                self.updatePrincipalMatrixRoles(name,item)
+                self.updatePrincipalMatrixPermissions(item)
             for group_id in self.principal.groups:
                 group = self.principals.getPrincipal(group_id)
                 self.principalMatrix['groups'][group_id] = \
                     self.policyPermissions(group, settings)
 
 
-    def populatePrincipalMatrixRoles(self, name, item):
+    def updatePrincipalMatrixRoles(self, name, item):
         for curRole in item.get('principalRoles', ()):
             if curRole['principal'] != self.principal.id:
                 continue
@@ -260,7 +327,7 @@
 
             if parentList:
                 # If we have a parent list we want to populate the tree
-                self.populatePrincipalRoleTree(item,parentList,curRole)
+                self.updateRoleTree(item,parentList,curRole)
 
             if curRole['setting'] == Deny:
                 try:
@@ -272,9 +339,9 @@
                     pass
                 continue
             else:
-                self.populatePrincipalRoles(item,role,curRole)
+                self.updateRoles(item,role,curRole)
 
-    def populatePrincipalRoleTree(self,item,parentList,curRole):
+    def updateRoleTree(self,item,parentList,curRole):
         """
         This method is responsible for poplating the roletree.
         """
@@ -284,11 +351,11 @@
         keys =  [x.keys()[0] for x in roleTree]
 
         # Each key is unique so we just get the list index to edit
-        if key not in keys:
+        if key in keys:
+            listIdx = keys.index(key)
+        else:
             roleTree.append({key:{}})
             listIdx = -1
-        else:
-            listIdx = keys.index(key)
 
         roleTree[listIdx][key]['parentList'] =  parentList
         roleTree[listIdx][key]['name'] = item.get('name')
@@ -298,10 +365,10 @@
         if curRole not in roleTree[listIdx][key]['roles']:
             roleTree[listIdx][key]['roles'].append(curRole)
 
-    def populatePrincipalRoles(self,item,role,curRole):
+    def updateRoles(self,item,role,curRole):
         if curRole['setting'] == Allow:
             # We only want to append the role if it is Allowed
-            roles = self.principalMatrix['roles']             
+            roles = self.principalMatrix['roles']
             rolePerms = self.roleSettings['rolePermissions']
 
             if not roles.has_key(role):
@@ -317,7 +384,7 @@
                     if mapping not in roles[role]:
                         roles[role].append(mapping)
 
-    def populatePrincipalMatrixPermissions(self, item):
+    def updatePrincipalMatrixPermissions(self, item):
         """ Here we get all the permissions for the given principal
             on the item passed.
         """
@@ -327,13 +394,13 @@
                 continue
 
             if item.get('parentList',None):
-                self.populatePrincipalPermTree(item,prinPerms)
+                self.updatePermissionTree(item,prinPerms)
 
             mapping = {'permission': prinPerms['permission'],
                        'setting'   : prinPerms['setting'],}
 
             dup = [perm for perm in self.principalMatrix['permissions'] \
-                   if perm['permission'] == mapping['permission']] 
+                   if perm['permission'] == mapping['permission']]
 
             if dup:
                 # This means we already have a record with this permission
@@ -343,111 +410,30 @@
             self.principalMatrix['permissions'].append(mapping)
 
 
-    def populatePrincipalPermTree(self,item,prinPerms):
+
+    def updatePermissionTree(self,item,prinPerms):
         """ method responsible for creating permission tree """
-        
+
         permissionTree = self.principalMatrix['permissionTree']
 
         key = item.get('uid')
         keys =  [x.keys()[0] for x in permissionTree]
 
         # Each key is unique so we just get the list index to edit
-        if key not in keys:
+        if key in keys:
+            listIdx = keys.index(key)
+        else:
             permissionTree.append({key:{}})
             listIdx = -1
-        else:
-            listIdx = keys.index(key)
 
         permissionTree[listIdx][key]['parentList'] = item.get('parentList')
         permissionTree[listIdx][key]['name'] = item.get('name')
         permissionTree[listIdx][key].setdefault('permissions',[])
-        
+
         if prinPerms not in permissionTree[listIdx][key]['permissions']:
               permissionTree[listIdx][key]['permissions'].append(prinPerms)
 
 
-    def permissionDetails(self, principal_id, view_name, skin=IBrowserRequest):
-        """Get permission details for a given principal and view.
-        Includes the permissions set by the groups the principal belongs to.
-        """
-        principals = zapi.principals()
-        principal = principals.getPrincipal(principal_id)
-
-        read_perm = settings = None
-        ifaces = tuple(providedBy(self.context))
-        for iface in ifaces:
-            for view_reg in getViews(iface, skin):
-                if view_reg.name == view_name:
-
-                    view = self.getView(view_reg, skin)
-                    settings = settingsForObject(view)
-                    read_perm = getViewInfoDictionary(view_reg)['read_perm']
-                    break
-
-        # Here we want to aggregate all the rolePermissions in one place
-        rolePermissions = []
-        if not settings:
-            return  {'read_perm':'zope.Public',
-                     'permissions': [],
-                     'roles': [],
-                     'groups': {}}
-
-        if read_perm is None:
-            prinPermSettings = {'permissions': [],
-                                'roles': [],
-                                'groups': {}}
-            read_perm ='zope.Public'
-        else:
-            for name,setting in settings:
-                if setting.get('rolePermissions',''):
-                    rolePermissions.extend(setting['rolePermissions'])
-
-            prinPermSettings = self._permissionDetails(principal,
-                                                       read_perm,
-                                                       settings,
-                                                       rolePermissions)
-
-        prinPermSettings['read_perm'] = read_perm
-
-        return prinPermSettings
-
-    def _permissionDetails(self,principal,read_perm,settings, rolePermissions):
-        """Recursively get the permission details for a given principal and
-        permission from a security mapping.
-        """
-        principalSettings = {'permissions': [],
-                             'roles': {},
-                             'groups': {}}
-        principals = zapi.principals()
-
-        for name, setting in settings:
-            prinPermMap = setting.get('principalPermissions', ())
-            prinRoleMap = setting.get('principalRoles', ())
-            rolePermMap = rolePermissions
-            permSetting = principalDirectlyProvidesPermission(prinPermMap,
-                principal.id, read_perm)
-            if permSetting:
-                principalSettings['permissions'].append(
-                    {'name': renderedName(name), 'setting': permSetting})
-
-            role_id, permSetting = principalRoleProvidesPermission(
-                prinRoleMap, rolePermMap, principal.id,read_perm )
-            if permSetting:
-                nameList = principalSettings['roles'].setdefault(role_id, [])
-                nameList.append({'name': renderedName(name),
-                                 'setting': permSetting})
-
-            for group_id in principal.groups:
-                group = principals.getPrincipal(group_id)
-                group_settings = self._permissionDetails(group,
-                    read_perm, settings, rolePermMap)
-
-                if hasPermissionSetting(group_settings):
-                    principalSettings['groups'][group_id] = group_settings
-
-        return principalSettings
-
-
 def getViews(iface, reqType=IRequest):
     """Get all view registrations for a particular interface."""
     gsm = getGlobalSiteManager()
@@ -581,7 +567,7 @@
     result[-1][1]['parentList'] = ['Root Folder']
     result[-1][1]['uid']        = 'Root  Folder'
     result[-1][1]['name']       = 'Root  Folder'
-    
+
     data = {}
     result.append(('global settings', data))
 
@@ -607,3 +593,37 @@
 
     return result
 
+def getSettingsForMatrix(viewInstance):
+    """ Here we aggregate all the principal permissions into one object
+        We need them all for our lookups to work properly in
+        principalRoleProvidesPermission.
+    """
+    allSettings = {}
+    permSetting = ()
+    settingList = [val for name ,val in settingsForObject(viewInstance)]
+
+    # The settings list is an aggregate of all settings
+    # so we can lookup permission settings for any role
+    for setting in settingList:
+        for key,val in setting.items():
+            if not allSettings.has_key(key):
+                allSettings[key] = []
+            allSettings[key].extend(val)
+
+    settings= settingsForObject(viewInstance)
+    settings.reverse()
+
+    return allSettings, settings
+
+def getView(context, view_reg, skin=IBrowserRequest):
+    """Instantiate view from given registration and skin.
+       Return `None` if the view isn't callable.
+    """
+    request = TestRequest()
+    applySkin(request, skin)
+    try:
+        view_inst = view_reg.factory(context, request)
+        if callable(view_inst):
+            return view_inst
+    except TypeError:
+        pass



More information about the Checkins mailing list