Back to index

plone3  3.1.7
rolemap.py
Go to the documentation of this file.
00001 ##############################################################################
00002 #
00003 # Copyright (c) 2004 Zope Corporation and Contributors. All Rights Reserved.
00004 #
00005 # This software is subject to the provisions of the Zope Public License,
00006 # Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
00007 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
00008 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00009 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
00010 # FOR A PARTICULAR PURPOSE.
00011 #
00012 ##############################################################################
00013 """ GenericSetup:  Role-permission export / import
00014 
00015 $Id: rolemap.py 82166 2007-12-06 17:58:50Z ldr $
00016 """
00017 
00018 from AccessControl import ClassSecurityInfo
00019 from AccessControl.Permission import Permission
00020 from Globals import InitializeClass
00021 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
00022 
00023 from permissions import ManagePortal
00024 from utils import _xmldir
00025 from utils import ExportConfiguratorBase
00026 from utils import ImportConfiguratorBase
00027 from utils import CONVERTER, DEFAULT, KEY
00028 
00029 
00030 #
00031 #   Configurator entry points
00032 #
00033 _FILENAME = 'rolemap.xml'
00034 
00035 def importRolemap( context ):
00036 
00037     """ Import roles / permission map from an XML file.
00038 
00039     o 'context' must implement IImportContext.
00040 
00041     o Register via Python:
00042 
00043       registry = site.setup_tool.setup_steps
00044       registry.registerStep( 'importRolemap'
00045                            , '20040518-01'
00046                            , Products.GenericSetup.rolemap.importRolemap
00047                            , ()
00048                            , 'Role / Permission import'
00049                            , 'Import additional roles, and map '
00050                            'roles to permissions'
00051                            )
00052 
00053     o Register via XML:
00054 
00055       <setup-step id="importRolemap"
00056                   version="20040518-01"
00057                   handler="Products.GenericSetup.rolemap.importRolemap"
00058                   title="Role / Permission import"
00059       >Import additional roles, and map roles to permissions.</setup-step>
00060 
00061     """
00062     site = context.getSite()
00063     encoding = context.getEncoding()
00064     logger = context.getLogger('rolemap')
00065 
00066     if context.shouldPurge():
00067 
00068         items = site.__dict__.items()
00069 
00070         for k, v in items: # XXX: WAAA
00071 
00072             if k == '__ac_roles__':
00073                 delattr( site, k )
00074 
00075             if k.startswith( '_' ) and k.endswith( '_Permission' ):
00076                 delattr( site, k )
00077 
00078     text = context.readDataFile( _FILENAME )
00079 
00080     if text is not None:
00081 
00082         rc = RolemapImportConfigurator(site, encoding)
00083         rolemap_info = rc.parseXML( text )
00084 
00085         immediate_roles = list( getattr(site, '__ac_roles__', []) )
00086         already = {}
00087 
00088         for role in site.valid_roles():
00089             already[ role ] = 1
00090 
00091         for role in rolemap_info[ 'roles' ]:
00092 
00093             if already.get( role ) is None:
00094                 immediate_roles.append( role )
00095                 already[ role ] = 1
00096 
00097         immediate_roles.sort()
00098         site.__ac_roles__ = tuple( immediate_roles )
00099 
00100         for permission in rolemap_info[ 'permissions' ]:
00101 
00102             site.manage_permission( permission[ 'name' ]
00103                                   , permission.get('roles', [])
00104                                   , permission[ 'acquire' ]
00105                                   )
00106 
00107     logger.info('Role / permission map imported.')
00108 
00109 
00110 def exportRolemap( context ):
00111 
00112     """ Export roles / permission map as an XML file
00113 
00114     o 'context' must implement IExportContext.
00115 
00116     o Register via Python:
00117 
00118       registry = site.setup_tool.export_steps
00119       registry.registerStep( 'exportRolemap'
00120                            , Products.GenericSetup.rolemap.exportRolemap
00121                            , 'Role / Permission export'
00122                            , 'Export additional roles, and '
00123                              'role / permission map '
00124                            )
00125 
00126     o Register via XML:
00127 
00128       <export-script id="exportRolemap"
00129                      version="20040518-01"
00130                      handler="Products.GenericSetup.rolemap.exportRolemap"
00131                      title="Role / Permission export"
00132       >Export additional roles, and role / permission map.</export-script>
00133 
00134     """
00135     site = context.getSite()
00136     logger = context.getLogger('rolemap')
00137 
00138     rc = RolemapExportConfigurator(site).__of__(site)
00139     text = rc.generateXML()
00140 
00141     context.writeDataFile( _FILENAME, text, 'text/xml' )
00142 
00143     logger.info('Role / permission map exported.')
00144 
00145 
00146 class RolemapExportConfigurator(ExportConfiguratorBase):
00147 
00148     """ Synthesize XML description of sitewide role-permission settings.
00149     """
00150     security = ClassSecurityInfo()
00151 
00152     security.declareProtected( ManagePortal, 'listRoles' )
00153     def listRoles( self ):
00154 
00155         """ List the valid role IDs for our site.
00156         """
00157         return self._site.valid_roles()
00158 
00159     security.declareProtected( ManagePortal, 'listPermissions' )
00160     def listPermissions( self ):
00161 
00162         """ List permissions for export.
00163 
00164         o Returns a sqeuence of mappings describing locally-modified
00165           permission / role settings.  Keys include:
00166 
00167           'permission' -- the name of the permission
00168 
00169           'acquire' -- a flag indicating whether to acquire roles from the
00170               site's container
00171 
00172           'roles' -- the list of roles which have the permission.
00173 
00174         o Do not include permissions which both acquire and which define
00175           no local changes to the acquired policy.
00176         """
00177         permissions = []
00178         valid_roles = self.listRoles()
00179 
00180         for perm in self._site.ac_inherited_permissions( 1 ):
00181 
00182             name = perm[ 0 ]
00183             p = Permission( name, perm[ 1 ], self._site )
00184             roles = p.getRoles( default=[] )
00185             acquire = isinstance( roles, list )  # tuple means don't acquire
00186             roles = [ r for r in roles if r in valid_roles ]
00187             roles.sort()
00188 
00189             if roles or not acquire:
00190                 permissions.append( { 'name'    : name
00191                                     , 'acquire' : acquire
00192                                     , 'roles'   : roles
00193                                     } )
00194 
00195         return permissions
00196 
00197     def _getExportTemplate(self):
00198 
00199         return PageTemplateFile('rmeExport.xml', _xmldir)
00200 
00201 InitializeClass(RolemapExportConfigurator)
00202 
00203 
00204 class RolemapImportConfigurator(ImportConfiguratorBase):
00205 
00206     """ Synthesize XML description of sitewide role-permission settings.
00207     """
00208     security = ClassSecurityInfo()
00209 
00210     def _getImportMapping(self):
00211 
00212         return {
00213           'rolemap':
00214             { 'roles':       {CONVERTER: self._convertToUnique, DEFAULT: ()},
00215               'permissions': {CONVERTER: self._convertToUnique} },
00216           'roles':
00217             { 'role':        {KEY: None} },
00218           'role':
00219             { 'name':        {KEY: None} },
00220           'permissions':
00221             { 'permission':  {KEY: None, DEFAULT: ()} },
00222           'permission':
00223             { 'name':        {},
00224               'role':        {KEY: 'roles'},
00225               'acquire':     {CONVERTER: self._convertToBoolean} } }
00226 
00227 InitializeClass(RolemapImportConfigurator)