def patch_class_security(self, klass, method_name, new_permission): """Monkey patch class security definitions to protect a method with a different permission. """ def reset_security_for_attribute(name, klass): """Remove security declarations for a particular method / attribute by filtering declarations for that attribute from __ac_permissions__. """ new_ac_permissions = [] for permission_mapping in klass.__ac_permissions__: permission, names = permission_mapping if name not in names: new_ac_permissions.append(permission_mapping) else: new_names = tuple([n for n in names if n != name]) modified_mapping = (permission, new_names) new_ac_permissions.append(modified_mapping) klass.__ac_permissions__ = tuple(new_ac_permissions) reset_security_for_attribute(method_name, klass) sec = ClassSecurityInfo() sec.declareProtected(new_permission, method_name) sec.apply(klass) InitializeClass(klass)
def test_security_defined_on_class(self): # wrapping a method in an interaction workflow adds a default security to # this method, but does not override existing security definition (defined # on the class) from erp5.component.document.Organisation import Organisation security = ClassSecurityInfo() security.declarePrivate('doSomethingStupid') security.apply(Organisation) self.createInteractionWorkflow() self.interaction.setProperties('default', method_id='doSomethingStupid', after_script_name=('afterEdit', )) self.script.ZPythonScript_edit('sci', '') self.assertEqual(self.organisation.doSomethingStupid__roles__, ())
def disablePasResources(event): """Disable access to users/groups/roles management PAS plugins from browser as they have no protection from CSRF attacks. """ try: zport = getattr(event.app, 'zport', None) if not zport or getattr(zport.dmd, 'allowManageAccess', False): return for class_ in (ZODBUserManager.ZODBUserManager, ZODBGroupManager.ZODBGroupManager, ZODBRoleManager.ZODBRoleManager): security = ClassSecurityInfo() security.declareObjectPrivate() security.apply(class_) except AttributeError: pass
def test_security_defined_on_class(self): # wrapping a method in an interaction workflow adds a default security to # this method, but does not override existing security definition (defined # on the class) Organisation = Products.ERP5.Document.Organisation.Organisation security = ClassSecurityInfo() security.declarePrivate('doSomethingStupid') security.apply(Organisation) self.createInteractionWorkflow() self.interaction.setProperties( 'default', method_id='doSomethingStupid', after_script_name=('afterEdit',)) self.script.ZPythonScript_edit('sci', '') self.createData() self.assertEqual(self.organisation.doSomethingStupid__roles__, ())
'zpt/mail_newCommentToParent', 'zpt/mail_rejectCommentToAuthor', 'zpt/mail_deleteCommentToAuthor', 'zpt/mail_approveCommentToAuthor', ) addTemplates2Class(CommentsStorage, templates, globals_=globals()) security = ClassSecurityInfo() security.declareProtected(VMS, 'tabComments') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'editCommentsForm') security.declarePrivate('mail_newCommentToWebmaster') security.declarePrivate('mail_newCommentToParent') security.declarePrivate('mail_rejectCommentToAuthor') security.declarePrivate('mail_deleteCommentToAuthor') security.declarePrivate('mail_approveCommentToAuthor') security.apply(CommentsStorage) import unittest import sys class CommentsStorageTests(unittest.TestCase): """ Test class for CommentsStorage class """ def test_addComment1(self): """ Add one comment """ comments = CommentsStorage() comments.addComment('title1','body1',
deletePage = BaseContainer.deleteItem security.declareProtected(PERMISSION_VIEW, 'countPages') countPages = BaseContainer.countItems templates = ( 'zpt/page/PagesManagementHome', 'zpt/page/addPageForm', 'zpt/page/deletePageForm',) addTemplates2Class(PageContainer, templates, globals_=globals()) security = ClassSecurityInfo() security.declareProtected(PERMISSION_MANAGE_CONTENT, 'PagesManagementHome') security.declareProtected(PERMISSION_MANAGE_CONTENT, 'addPageForm') security.declareProtected(PERMISSION_MANAGE_CONTENT, 'deletePageForm') security.apply(PageContainer) InitializeClass(PageContainer) ###################################################################### ## Page ###################################################################### manage_addPageForm = PTF('zpt/page/addPageForm', globals()) def manage_addPage(context, id, title, abstract = u'', body=u'',publish_date=None, REQUEST=None): """ create """ if isinstance(title, str): title = unicodify(title) if isinstance(abstract, str):
for mapping in Container.__ac_permissions__: perm, attrs = mapping if attribute not in attrs: new_mappings.append(mapping) else: modified_attrs = tuple([a for a in attrs if not a == attribute]) modified_mapping = (perm, modified_attrs) new_mappings.append(modified_mapping) classobj.__ac_permissions__ = tuple(new_mappings) drop_protected_attr_from_ac_permissions("manage_pasteObjects", Container) sec = ClassSecurityInfo() sec.declareProtected(Products.CMFCore.permissions.AddPortalContent, "manage_pasteObjects") sec.apply(Container) InitializeClass(Container) def initialize(context): context.registerClass( roleplugin.CityMayorUserFactory, permission=add_user_folders, constructors=( roleplugin.manage_addCityMayorUserFactoryForm, roleplugin.manage_addCityMayorUserFactory, ), visibility=None, )
result.append(object) if year and not month: if publish_date.year() == year: result.append(object) return result templates = ('zpt/BlogManagement', 'zpt/deleteBlogItemForm', ) addTemplates2Class(BlogContainer, templates, globals_=globals()) setattr(BlogContainer, 'rss.xml', BlogContainer.RSS) security = ClassSecurityInfo() security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deleteBlogItemForm') security.apply(BlogContainer) InitializeClass(BlogContainer) #------------------------------------------------------------------------------- manage_addBlogItemForm = PTF('zpt/addBlogItemForm', globals()) def manage_suggestBlogItemId(self): """ suggest a new id """ return DateTime().strftime('blog-%d%b%Y')
return self.utSortObjsListByAttr(self.getPublishedContent(), skey, rkey) NyFolder.getSortedPublishedContent = getSortedPublishedContent def getSortedPendingContent(self, skey='', rkey=0): return self.utSortObjsListByAttr(self.getPendingContent(), skey, rkey) NyFolder.getSortedPendingContent = getSortedPendingContent def getSortedDuplicateContent(self, skey='', rkey=0): return self.utSortObjsListByAttr(self.getDuplicatesInFolder(), skey, rkey) NyFolder.getSortedDuplicateContent = getSortedDuplicateContent security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'processDuplicateContent') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'getDuplicatesInFolder') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_published_html') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_duplicates_html') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'processPublishedContent') security.apply(NyFolder) InitializeClass(NyFolder)
return '%s/%s'%(icon_location, ICON_ASSOCIATIONS[extension]) else: return default #security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagement') templates = ('zpt/FileManagement', 'zpt/deleteFileForm', ) addTemplates2Class(FilesContainer, templates, globals_=globals()) security = ClassSecurityInfo() security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagement') security.apply(FilesContainer) InitializeClass(FilesContainer) #------------------------------------------------------------------------------- manage_addFileForm = PTF('zpt/addFileForm', globals()) def manage_addFile(dispatcher, title, file, fileid='', abstract=u'', REQUEST=None): """ create """ dest = dispatcher.Destination() if not fileid:
deleteFAQ = BaseContainer.deleteItem security.declareProtected(PERMISSION_VIEW, 'countFAQ') countFAQ = BaseContainer.countItems templates = ('zpt/faq/FAQManagement', #'zpt/faq/addPageForm', 'zpt/faq/deleteFAQForm', ) addTemplates2Class(FAQContainer, templates, globals_=globals()) security = ClassSecurityInfo() #security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'addFAQForm') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deleteFAQForm') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FAQManagement') security.apply(FAQContainer) InitializeClass(FAQContainer) ###################################################################### ## FAQ ###################################################################### manage_addFAQForm = PTF('zpt/faq/addFAQForm', globals()) def manage_addFAQ(dispatcher, id, title, abstract='', body='', publish_date=None, category = None, REQUEST=None): """ Create FAQ object """ if hasattr(dispatcher, 'Destination'):
self.recatalogNyObject(ob) except: pass for id in self.utConvertToList(delids): try: self._delObject(id) except: pass if REQUEST: self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate()) REQUEST.RESPONSE.redirect('%s/basketofapprovals_published_html' % self.absolute_url()) NyFolder.processPublishedContent = processPublishedContent def getSortedPublishedContent(self, skey='', rkey=0): return self.utSortObjsListByAttr(self.getPublishedContent(), skey, rkey) NyFolder.getSortedPublishedContent = getSortedPublishedContent def getSortedPendingContent(self, skey='', rkey=0): return self.utSortObjsListByAttr(self.getPendingContent(), skey, rkey) NyFolder.getSortedPendingContent = getSortedPendingContent def getSortedDuplicateContent(self, skey='', rkey=0): return self.utSortObjsListByAttr(self.getDuplicatesInFolder(), skey, rkey) NyFolder.getSortedDuplicateContent = getSortedDuplicateContent security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'processDuplicateContent') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'getDuplicatesInFolder') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_published_html') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_duplicates_html') security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'processPublishedContent') security.apply(NyFolder) InitializeClass(NyFolder)
for each in COMMON_USER_AGENTS: tofind, nick = each if user_agent.find(tofind) > -1: return nick return user_agent[:45] security.declareProtected(VMS, 'manage_UpdatePlogRank') def manage_UpdatePlogRank(self): """ use PlogMatrix to calculate every plogrank """ return UpdatePlogRank(self) zpts = (('zpt/blogcontainer_index', 'index_html'), ) addTemplates2Class(PeterbeBlogContainer, zpts, extension='zpt') dtmls = ( ('dtml/blogcontainer_stats', 'manage_Statistics'), 'dtml/blogcontainer_calendar', ) addTemplates2Class(PeterbeBlogContainer, dtmls, extension='dtml') setattr(PeterbeBlogContainer, 'rss.xml', PeterbeBlogContainer.RSS10) security = ClassSecurityInfo() security.declareProtected(VMS, 'manage_Statistics') security.apply(PeterbeBlogContainer) InitializeClass(PeterbeBlogContainer)
security.declareProtected(VMS, 'manage_UpdatePlogRank') def manage_UpdatePlogRank(self): """ use PlogMatrix to calculate every plogrank """ return UpdatePlogRank(self) zpts = (('zpt/blogcontainer_index', 'index_html'),) addTemplates2Class(PeterbeBlogContainer, zpts, extension='zpt') dtmls = (('dtml/blogcontainer_stats','manage_Statistics'), 'dtml/blogcontainer_calendar', ) addTemplates2Class(PeterbeBlogContainer, dtmls, extension='dtml') setattr(PeterbeBlogContainer, 'rss.xml', PeterbeBlogContainer.RSS10) security = ClassSecurityInfo() security.declareProtected(VMS, 'manage_Statistics') security.apply(PeterbeBlogContainer) InitializeClass(PeterbeBlogContainer)
LOGGER.info('Monkey patched webdav.LockItem.DEFAULTTIMEOUT') # -------- from plone.dexterity.content import Container # Change permission for manage_pasteObjects to "Add portal content" # See https://dev.plone.org/ticket/9177 # XXX Find a way to do this without patching __ac_permissions__ directly def drop_protected_attr_from_ac_permissions(attribute, classobj): new_mappings = [] for mapping in Container.__ac_permissions__: perm, attrs = mapping if not attribute in attrs: new_mappings.append(mapping) else: modified_attrs = tuple([a for a in attrs if not a == attribute]) modified_mapping = (perm, modified_attrs) new_mappings.append(modified_mapping) classobj.__ac_permissions__ = tuple(new_mappings) drop_protected_attr_from_ac_permissions('manage_pasteObjects', Container) sec = ClassSecurityInfo() sec.declareProtected(Products.CMFCore.permissions.AddPortalContent, 'manage_pasteObjects') sec.apply(Container) InitializeClass(Container) LOGGER.info('Monkey patched plone.dexterity.content.Container')
- outlives transaction duration - bound to a thread only while a transaction is executed (ie, it can be reused by a different thread on next processed transaction) - destroyed when object is modified by another transaction - destroyed when object is modified by transaction and transaction gets aborted - destroyed when connection cache is minimized and holder (self) is pruned (minimization can be triggered in many places...) Of course, you should only cache values which *only* depends on self's pertistent properties, and no other object (persistent or not). Otherwise your cache will not be flushed when it needs to. """ try: cache_dict = self._v_SimpleItem_Item_vCache except AttributeError: # It's safe to use a non-persistence-aware instance, we are setting a # volatile property anyway. self._v_SimpleItem_Item_vCache = cache_dict = {} # Use whole func_code as a key, as it is the only reliable way to identify a # function. key = func.func_code try: return cache_dict[key] except KeyError: cache_dict[key] = value = func() return value SimpleItem.volatileCached = volatileCached security.apply(SimpleItem)
- bound to a thread only while a transaction is executed (ie, it can be reused by a different thread on next processed transaction) - destroyed when object is modified by another transaction - destroyed when object is modified by transaction and transaction gets aborted - destroyed when connection cache is minimized and holder (self) is pruned (minimization can be triggered in many places...) Of course, you should only cache values which *only* depends on self's pertistent properties, and no other object (persistent or not). Otherwise your cache will not be flushed when it needs to. """ try: cache_dict = self._v_SimpleItem_Item_vCache except AttributeError: # It's safe to use a non-persistence-aware instance, we are setting a # volatile property anyway. self._v_SimpleItem_Item_vCache = cache_dict = {} # Use whole func_code as a key, as it is the only reliable way to identify a # function. key = func.__code__ try: return cache_dict[key] except KeyError: cache_dict[key] = value = func() return value SimpleItem.volatileCached = volatileCached security.apply(SimpleItem)
'zpt/ManagementHeaderFooter', 'zpt/DocumentManagementHome', ('dtml/cms.js', 'cms_js_template'), 'zpt/page/PagesManagementHome', 'zpt/page/deletePageForm', 'zpt/faq/FAQManagementHome', ) addTemplates2Class(Homepage, templates) security = ClassSecurityInfo() security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'Management') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'NewsManagementHome') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'BlogManagementHome') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagementHome') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'DocumentManagementHome') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'PagesManagementHome') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FAQManagementHome') #security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'addPageForm') security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deletePageForm') security.apply(Homepage) setattr(Homepage, 'cms.js', Homepage.cms_js) InitializeClass(Homepage) #-------------------------------------------------------------------------------
return True if q.find('/') > -1 and entry['url'].find(q) > -1: return True #print entry['url'] #print entry['id'] #print entry['req_html'] res = [entry.copy() for entry in self._getLog() if matchingQuery(entry, q)] else: res = [entry.copy() for entry in self._getLog()] res.reverse() return res setattr(SiteErrorLog, 'getLogEntries', getLogEntries) # Add the getLogEntryErrorTypes from Products.SiteErrorLog.SiteErrorLog import use_error_logging security.declareProtected(use_error_logging, 'getLogEntryErrorTypes') def getLogEntryErrorTypes(self): types = [] for entry in self._getLog(): if entry['type'] not in types: types.append(entry['type']) return types setattr(SiteErrorLog, 'getLogEntryErrorTypes', getLogEntryErrorTypes) # Set the security security.apply(SiteErrorLog)
if REQUEST is not None: msg = "News item deleted" url = self.absolute_url()+'/NewsManagement' self.http_redirect(url, msg=msg) templates = ('zpt/NewsManagement', 'zpt/deleteNewsItemForm', ) addTemplates2Class(NewsContainer, templates, globals_=globals()) setattr(NewsContainer, 'rss.xml', NewsContainer.RSS) security = ClassSecurityInfo() security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deleteNewsItemForm') security.apply(NewsContainer) InitializeClass(NewsContainer) #------------------------------------------------------------------------------- manage_addNewsItemForm = PTF('zpt/addNewsItemForm', globals()) def manage_suggestNewsItemId(self): """ suggest a new id """ return DateTime().strftime('newsitem-%d%b%Y') def manage_addNewsItem(dispatcher, title,
img.save(imagefilepath, fmt) thumbimage = open(imagefilepath, 'rb') ext = p.getId().split('.')[-1] id = 'tumnagel.%s' % ext self.uploadThumbnail(file=thumbimage.read(), id=id) templates = (#'dtml/something', 'zpt/editBustForm', ) addTemplates2Class(Bust, templates) security = ClassSecurityInfo() security.declareProtected(VMS, 'editBustForm') security.apply(Bust) InitializeClass(Bust) #----------------------------------------------------------------------------- manage_addBustFolderForm = PTF('zpt/addBustFolderForm', globals()) def manage_addBustFolder(dispatcher, id, title, REQUEST=None, redirect_to=None): """ create instance """ dest = dispatcher.Destination() instance = BustFolder(id, title) dest._setObject(id, instance)
return label # default return value else: return value zpts = ("zpt/customfield/manage_field", "zpt/customfield/manage_validation", "zpt/customfield/index_html") addTemplates2Class(CustomField, zpts) security = ClassSecurityInfo() security.declareProtected(VMS, "index_html") security.declareProtected(VMS, "manage_field") security.declareProtected(VMS, "manage_validation") security.apply(CustomField) InitializeClass(CustomField) # ---------------------------------------------------------------------------- from OFS.SimpleItem import SimpleItem from OFS.PropertyManager import PropertyManager class ValidationExpression(SimpleItem, PropertyManager): """ a validation expression is a very simple object that consists of two things: expression (str) and message (unicode) """