def addOrder(self, customer=None, cart=None): """ """ cartmanager = ICartManagement(self.context) if customer is None: cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() if cart is None: cart = cartmanager.getCart() portal = getToolByName(self.context, 'portal_url').getPortalObject() ## The current user may not be allowed to create an order, so we ## temporarily change the security context to use a temporary ## user with manager role. old_sm = getSecurityManager() tmp_user = UnrestrictedUser(old_sm.getUser().getId(), '', ['Manager'], '') tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) # Add a new order new_id = self._createOrderId() self.orders.invokeFactory("Order", id=new_id) new_order = getattr(self.orders, new_id) # Copy Customer to Order customer = ICustomerManagement(self.context).getAuthenticatedCustomer() cm = ICopyManagement(customer) cm.copyTo(new_order) # Add cart items to order IItemManagement(new_order).addItemsFromCart(cart) # Add total tax new_order.setTax(ITaxes(cart).getTaxForCustomer()) # Add shipping values to order sm = IShippingPriceManagement(self.context) new_order.setShippingPriceNet(sm.getPriceNet()) new_order.setShippingPriceGross(sm.getPriceForCustomer()) new_order.setShippingTax(sm.getTaxForCustomer()) new_order.setShippingTaxRate(sm.getTaxRateForCustomer()) # Add payment price values to order pp = IPaymentPriceManagement(self.context) new_order.setPaymentPriceGross(pp.getPriceForCustomer()) new_order.setPaymentPriceNet(pp.getPriceNet()) new_order.setPaymentTax(pp.getTaxForCustomer()) new_order.setPaymentTaxRate(pp.getTaxRateForCustomer()) ## Reset security manager setSecurityManager(old_sm) # Index with customer again new_order.reindexObject() return new_order
def afterSetUp(self, quiet=1, run=run_all_test): """ Create ERP5 user. This has to be called only once. """ # setup new active process for this test, in order have # consistency report local for one test sm = getSecurityManager() self.login() try: self.portal.portal_alarms.vifib_check_consistency.newActiveProcess() finally: setSecurityManager(sm) self.setupPortalCertificateAuthority() import random self.portal.portal_caches.erp5_site_global_id = '%s' % random.random() self.portal.portal_caches._p_changed = 1 transaction.commit() self.portal.portal_caches.updateCache() self.createAlarmStep() if getattr(self.portal, 'set_up_once_called', 0): return else: self.portal.set_up_once_called = 1 self.bootstrapSite() self.portal._p_changed = 1 transaction.commit() self.stabiliseAccounting()
def consumeActions(self, content, token, **kwargs): self.verifyToken(content, token) actions = self.consumeToken(content, token) results = [] for action in actions: action_type = action.type try: adapter = getMultiAdapter((content, content.REQUEST), IPowerActionProvider, name=action_type) except ComponentLookupError: raise ComponentLookupError('Cannot find a provider for performing action "%s" on %s' % (action_type, '/'.join(content.getPhysicalPath()))) try: if action.roles or action.unrestricted: acl_users = getToolByName(content, 'acl_users') old_sm = getSecurityManager() Cls = SimpleUser if action.unrestricted: Cls = UnrestrictedUser tmp_user = Cls(action.username or old_sm.getUser().getId() or '', '', action.roles, '') tmp_user = tmp_user.__of__(acl_users) newSecurityManager(None, tmp_user) results.append(adapter.doAction(action, **kwargs)) finally: if action.roles: setSecurityManager(old_sm) return results
def set_participation_marker(self): context = aq_inner(self.context) uuid = self.request.get('uuid', None) catalog = api.portal.get_tool(name='portal_catalog') results = catalog.unrestrictedSearchResults(UID=uuid) tool = getUtility(ISurveyTool) session = tool.get() marker = True owner = context.getWrappedOwner() sm = getSecurityManager() newSecurityManager(self.request, owner) try: item = results[0].getObject() if 'token' in session: token = session['token'] if token == self.token: state = {} data = json.loads(item.answers) results = data['survey-state'] state['idx'] = results['puid'] state['token'] = token state['ip'] = results['pip'] tool.add('token', state) tool.remove('survey-state') marker = False self.initial = True finally: setSecurityManager(sm) return marker
def receivePayment(self): """ """ shop = self.context # Get cart - Note: self.request.get("order") doesn't work! order_uid = self.request.get("QUERY_STRING")[6:] order = IOrderManagement(shop).getOrderByUID(order_uid) # change order state to "payed_not_sent" wftool = getToolByName(self, "portal_workflow") # We need a new security manager here, because this transaction should # usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser(old_sm.getUser().getId(), '', ['Manager'], '') portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) wftool.doActionFor(order, "pay_not_sent") ## Reset security manager setSecurityManager(old_sm)
def formatComputer(self, computer, partition_count=10): computer_dict = dict( software_root='/opt', reference=computer.getReference(), netmask='255.255.255.0', address='128.0.0.1', instance_root='/srv' ) computer_dict['partition_list'] = [] a = computer_dict['partition_list'].append for i in range(1, partition_count+1): a(dict( reference='part%s' % i, tap=dict(name='tap%s' % i), address_list=[ dict(addr='p%sa1' % i, netmask='p%sn1' % i), dict(addr='p%sa2' % i, netmask='p%sn2' % i) ] )) sm = getSecurityManager() try: self.login(computer.getUserId()) self.portal.portal_slap.loadComputerConfigurationFromXML( xml_marshaller.xml_marshaller.dumps(computer_dict)) self.tic() self.assertEqual(partition_count, len(computer.contentValues(portal_type='Computer Partition'))) finally: setSecurityManager(sm)
def update(self): #Zerando a variavel de retorno self.retorno = {} dados = {} username = self.request.form.get('username','') dados['username'] = username dados['name'] = self.request.form.get('name', username) dados['email'] = self.request.form.get('email', '') dados['password'] = self.request.form.get('password', '') if username: portal_membership = getToolByName(self.context, "portal_membership") user_admin = portal_membership.getMemberById('admin') # stash the existing security manager so we can restore it old_security_manager = getSecurityManager() # create a new context, as the owner of the folder newSecurityManager(self.request,user_admin) result = ImportUser().importUser(self,{},user=dados) # restore the original context setSecurityManager(old_security_manager) if result: self.retorno['response'] = 'Usuario criado com sucesso' else: self.retorno['response'] = 'Usuario não criado, dados invalidos' else: self.retorno['response'] = 'Usuario não criado, dados invalidos'
def receivePayment(self): """ """ shop = self.context # Get cart - Note: self.request.get("order") doesn't work! order_uid = self.request.get("QUERY_STRING")[6:] order = IOrderManagement(shop).getOrderByUID(order_uid) # change order state to "payed_not_sent" wftool = getToolByName(self, "portal_workflow") # We need a new security manager here, because this transaction should # usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) wftool.doActionFor(order, "pay_not_sent") ## Reset security manager setSecurityManager(old_sm)
def consumeActions(self, content, token, **kwargs): self.verifyToken(content, token) actions = self.consumeToken(content, token) results = [] for action in actions: action_type = action.type try: adapter = getMultiAdapter((content, content.REQUEST), IPowerActionProvider, name=action_type) except ComponentLookupError: raise ComponentLookupError( 'Cannot find a provider for performing action "%s" on %s' % (action_type, '/'.join(content.getPhysicalPath()))) try: if action.roles or action.unrestricted: acl_users = getToolByName(content, 'acl_users') old_sm = getSecurityManager() Cls = SimpleUser if action.unrestricted: Cls = UnrestrictedUser tmp_user = Cls( action.username or old_sm.getUser().getId() or '', '', action.roles, '') tmp_user = tmp_user.__of__(acl_users) newSecurityManager(None, tmp_user) results.append(adapter.doAction(action, **kwargs)) finally: if action.roles: setSecurityManager(old_sm) return results
def update(self): #Zerando a variavel de retorno self.retorno = {} portal_membership = getToolByName(self.context, "portal_membership") user_admin = portal_membership.getMemberById('admin') # stash the existing security manager so we can restore it old_security_manager = getSecurityManager() # create a new context, as the owner of the folder newSecurityManager(self.request,user_admin) group = self.request.form.get('group','') groups_tool = getToolByName(self.context, 'portal_groups') group_obj = groups_tool.getGroupById(group) members = group_obj.getGroupMembers() L = [] for member in members: L.append({'username':member.getUserName(), 'email':member.getProperty('email'), 'fullname': member.getProperty('fullname') }) # restore the original context setSecurityManager(old_security_manager) self.retorno = L
def __call__(self): """ wget http://myplone:8080/Plone/@@groups-update?key=abcdef -O - Voir les logs... """ portal = api.portal.get() request = self.request required_key = getSettingValue('updates_key') key = request.get('key') if key != required_key: msg = "Access key doesn't match required key !!!!" logger.info(msg) return msg portal = api.portal.get() sm = getSecurityManager() try: # go Admin, even in anymomous mode ! tmp_user = UnrestrictedUser(sm.getUser().getId(), '', ['Manager'], '') tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) plone_groups = api.group.get_groups() for plone_group in plone_groups: self.update_group(plone_group) transaction.commit() finally: # Restore the old security manager setSecurityManager(sm) now = datetime.datetime.now() # self.request.response.redirect(portal.absolute_url()) return 'groups updated at ' + str(now)
def handleSurveyUnpublish(survey, event): """Event handler (subscriber) to take care of unpublishing a survey from the client. """ surveygroup = aq_parent(survey) sector = aq_parent(surveygroup) country = aq_parent(sector) pas = getToolByName(survey, "acl_users") clientuser = pas.getUserById("client") sm = getSecurityManager() try: newSecurityManager(None, clientuser) client = getPortal(survey).client try: clientcountry = client[country.id] clientsector = clientcountry[sector.id] clientsector[surveygroup.id] except KeyError: log.info( "Trying to unpublish unpublished survey %s", "/".join(survey.getPhysicalPath()), ) return clientsector.manage_delObjects([surveygroup.id]) if not clientsector.keys(): clientcountry.manage_delObjects([clientsector.id]) finally: setSecurityManager(sm)
def PublishToClient(survey, preview=False): """Publish a survey in the online client part of the site. :param survey: the survey to copy :param bool preview: indicates if this is a preview or a normal publication :rtype: :py:class:`euphorie.content.survey.Survey` This is a wrapper around :py:func:`CopyToClient`, which temporarily changes the currently active Zope user to make sure content can be created in the client. """ pas = getToolByName(survey, "acl_users") clientuser = pas.getUserById("client") sm = getSecurityManager() tti = getUtility(IToolTypesInfo) tool_types_info = tti() tool_type_data = tool_types_info.get( survey.tool_type, tool_types_info.get(tti.default_tool_type)) try: newSecurityManager(None, clientuser) survey = CopyToClient(survey, preview) if tool_type_data.get("use_omega_risks", True): EnableCustomRisks(survey) survey.published = (survey.id, survey.title, datetime.datetime.now()) finally: setSecurityManager(sm) return survey
def __call__(self): om = IOrderManagement(self.context) tid = self.request.get('TID','') order = getattr(om.orders,tid,None) log("\n%s\n%s\n%s" % (order, tid, self.request.get('STATUS'))) if order and self.request.get('STATUS') in ['RESERVED','BILLED']: # Set order to payed (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") # We need a new security manager here, because this transaction # should usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) try: # set to pending (send emails) wftool.doActionFor(order, "submit") # set to payed wftool.doActionFor(order, "pay_not_sent") except Exception, msg: self.status = msg # Reset security manager setSecurityManager(old_sm)
def __call__(self): self.iu = get_import_utility() json_data = self.request.get("BODY", "") if not json_data: return data = json.loads(json_data) # SWITCH to Manager old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) # DO Stuff as Manager self.iu.create_content(data, self.context) # @TODO: Maybe add option to commit after all created # SWITCH Back setSecurityManager(old_sm) return ""
def handleApply(self, action): sm = getSecurityManager() portal = api.portal.get() data, errors = self.extractData() if errors: self.status = _("Please correct errors") return try: inner_contenttype = self.filter_inner_contenttype(data) try: # go Admin, even in anymomous mode ! tmp_user = UnrestrictedUser( sm.getUser().getId(), '', ['Manager'], '') tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) # Call the function # for edit form, use : self.applyChanges(data) obj = self.createAndAdd(data) # context is the mainobj repo obj = obj.__of__(self.context) self.applyInner_contenttype(obj, inner_contenttype) contextURL = self.context.absolute_url() self.request.response.redirect(contextURL) except Exception: # If special exception handlers are needed, run them here raise finally: # Restore the old security manager setSecurityManager(sm)
def elevated_privileges(user_id=None): """Temporarily elevate current user's privileges. If the `user_id` argument is set, it will be user as the ID of the temporary user with elevated_privileges, otherwise the current user's ID will be used. See http://docs.plone.org/develop/plone/security/permissions.html#bypassing-permission-checks for more documentation on this code. """ old_manager = getSecurityManager() try: # Clone the current user and assign a new role. # Note that the username (getId()) is left in exception # tracebacks in the error_log, # so it is an important thing to store. if user_id is None: user_id = api.user.get_current().getId() tmp_user = UnrestrictedUser(user_id, '', ('manage', 'Manager'), '') # Wrap the user in the acquisition context of the portal tmp_user = tmp_user.__of__(api.portal.get().acl_users) newSecurityManager(getRequest(), tmp_user) yield finally: # Restore the old security manager setSecurityManager(old_manager)
def handleSurveyUnpublish(survey, event): """Event handler (subscriber) to take care of unpublishing a survey from the client. """ surveygroup = aq_parent(survey) sector = aq_parent(surveygroup) country = aq_parent(sector) pas = getToolByName(survey, "acl_users") clientuser = pas.getUserById("client") sm = getSecurityManager() try: newSecurityManager(None, clientuser) client = getPortal(survey).client try: clientcountry = client[country.id] clientsector = clientcountry[sector.id] clientsector[surveygroup.id] except KeyError: log.info("Trying to unpublish unpublished survey %s", "/".join(survey.getPhysicalPath())) return clientsector.manage_delObjects([surveygroup.id]) if not clientsector.keys(): clientcountry.manage_delObjects([clientsector.id]) finally: setSecurityManager(sm)
def ImportSector(plone, options, filename): input = open(filename, "r") dom = lxml.objectify.parse(input) xml_sector = dom.getroot() country = GetCountry(plone, options) if not hasattr(xml_sector, "survey"): return sector = GetSector(country, xml_sector, options) if sector is None: raise Abort("No sector specified and no account information found.") # Login as the sector sup = UserProvider(sector) sectoruser = plone.acl_users.getUserById(sup.getUserId()) sm = getSecurityManager() try: newSecurityManager(None, sectoruser) name = options.name or unicode(xml_sector.survey.title.text) if hasattr(sector, name): raise Abort("There is already a survey named '%s'" % name) log.info(u"Importing survey '%s' with version '%s'", name, options.version) importer = SurveyImporter(sector) survey = importer(xml_sector, name, options.version) if options.publish: log.info("Publishing survey") publisher = publish.PublishSurvey(survey, None) publisher.publish() finally: setSecurityManager(sm)
def __exit__(self, exc_type, exc_value, exc_tb): """Back to former security context """ setSecurityManager(self.real_sm) # False: Re-raises exceptions that occured in the "with" block return False
def getEmailsForRole(self, role): portal = getSite() acl_users = getToolByName(portal, 'acl_users') # get a set of ids of members with the global role ids = set([p[0] for p in acl_users.portal_role_manager.listAssignedPrincipals(role)]) # union with set of ids of members with the local role ids |= set([user_id for user_id, irole in acl_users._getAllLocalRoles(self.context).items() if role in irole]) # get members from group or member ids members = _recursiveGetMembersFromIds(portal, ids) # get only allowed members allowed_members = [] old_sm = getSecurityManager() try: for m in members: # m is a MemberData instance, # it doesn't have an allowed method on it, # so checkPermission doesn't properly work. # PloneUser have this method. user = acl_users.getUserById(m.getId()) newSecurityManager(None, user) sm = getSecurityManager() if sm.checkPermission('View', self.context): allowed_members.append(m) finally: setSecurityManager(old_sm) # get emails return u', '.join(self.getPropsForMembers(allowed_members, 'email'))
def simulateSlapgridUR(self, computer): sm = getSecurityManager() computer_user_id = computer.getUserId() try: self.login(computer_user_id) computer_xml = self.portal.portal_slap.getFullComputerInformation( computer_id=computer.getReference()) if not isinstance(computer_xml, str): computer_xml = computer_xml.getBody() slap_computer = xml_marshaller.xml_marshaller.loads(computer_xml) self.assertEqual('Computer', slap_computer.__class__.__name__) destroyed_partition_id_list = [] for partition in slap_computer._computer_partition_list: if partition._requested_state == 'destroyed' \ and partition._need_modification == 1: self.portal.portal_slap.destroyedComputerPartition(computer.getReference(), partition._partition_id.encode("UTF-8") ) destroyed_partition_id_list.append(partition._partition_id.encode("UTF-8")) finally: setSecurityManager(sm) self.tic() self.stepCallSlaposFreeComputerPartitionAlarm() self.tic() free_partition_id_list = [] for partition in computer.contentValues(portal_type='Computer Partition'): if partition.getReference() in destroyed_partition_id_list \ and partition.getSlapState() == 'free': free_partition_id_list.append(partition.getReference()) self.assertSameSet(destroyed_partition_id_list, free_partition_id_list)
def handle_modified(self, content): fieldmanager = ILanguageIndependentFieldsManager(content) if not fieldmanager.has_independent_fields(): return sm = getSecurityManager() try: # Do we have permission to sync language independent fields? if self.bypass_security_checks(): # Clone the current user and assign a new editor role to # allow edition of all translated objects even if the # current user whould not have permission to do that. tmp_user = UnrestrictedUser( sm.getUser().getId(), '', ['Editor', ], '') # Wrap the user in the acquisition context of the portal # and finally switch the user to our new editor acl_users = getToolByName(content, 'acl_users') tmp_user = tmp_user.__of__(acl_users) newSecurityManager(None, tmp_user) # Copy over all language independent fields transmanager = ITranslationManager(content) for translation in self.get_all_translations(content): trans_obj = transmanager.get_translation(translation) if fieldmanager.copy_fields(trans_obj): self.reindex_translation(trans_obj) finally: # Restore the old security manager setSecurityManager(sm)
def verified_subject(self, claimset, service_key): """Verify the claim's subject and return it. If the subject does not match the userid of the service_key, the 'Impersonate user' permission is required. """ subject = claimset['sub'] actor = service_key['user_id'] if subject != actor: # Check if actor is allowed to impersonate uf = getToolByName(self.context, 'acl_users') user = uf.getUserById(actor) if not user: raise (InvalidGrant('Service key user not found.')) user = user.__of__(uf) old_security_manager = getSecurityManager() newSecurityManager(self.request, user) try: if not getSecurityManager().checkPermission( ImpersonateUser, self.context): raise InvalidGrant( "JWT subject doesn't match user_id of service key.") finally: setSecurityManager(old_security_manager) return subject
def unrestricted_apply(function, args=(), kw={}): """Function to bypass all security checks This function is as dangerous as 'UnrestrictedMethod' decorator. Read its docstring for more information. Never use this, until you are 100% certain that you have no other way. """ security_manager = getSecurityManager() user = security_manager.getUser() anonymous = (user.getUserName() == 'Anonymous User') if user.getId() is None and not anonymous: # This is a special user, thus the user is not allowed to own objects. super_user = UnrestrictedUser(user.getUserName(), None, user.getRoles(), user.getDomains()) else: try: # XXX is it better to get roles from the parent (i.e. portal)? uf = user.aq_inner.aq_parent except AttributeError: uf = app().acl_users role_list = uf.valid_roles() if anonymous: # If the user is anonymous, use the id of the system user, # so that it would not be treated as an unauthorized user. user_id = str(system) else: user_id = user.getId() super_user = PrivilegedUser(user_id, None, role_list, user.getDomains()).__of__(uf) newSecurityManager(None, super_user) try: return apply(function, args, kw) finally: # Make sure that the original user is back. setSecurityManager(security_manager)
def _getGroupsForPrincipal(user_name, path): if user_name.startswith(LOGIN_PREFIX): user_name = user_name[LOGIN_PREFIX_LENGTH:] else: return ( ) # because we aren't logged in, we have to create our own # SecurityManager to be able to access the Catalog sm = getSecurityManager() if sm.getUser().getId() != SUPER_USER: newSecurityManager(self, self.getUser(SUPER_USER)) try: # get the loggable document from its reference - no security check needed catalog_result = self.portal_catalog.unrestrictedSearchResults( portal_type=self.loggable_portal_type_list, reference=dict(query=user_name, key='ExactMatch')) if len(catalog_result) != 1: # we won't proceed with groups if len(catalog_result) > 1: # configuration is screwed raise ConsistencyError, 'There is more than one of %s whose \ login is %s : %s' % (','.join(self.loggable_portal_type_list), user_name, repr([r.getObject() for r in catalog_result])) else: return () else: portal_type = catalog_result[0].getPortalType() finally: setSecurityManager(sm) return ( 'R-SHADOW-%s' % portal_type.replace(' ', '').upper(), # generic group 'SHADOW-%s' % user_name # user specific shadow )
def login(self, user): old_manager = getSecurityManager() try: login(getSite(), user.getId()) yield finally: setSecurityManager(old_manager)
def getExpressConfigurationPreference(self, preference_id, default = None): """ Get Express configuration preference """ original_security_manager = _setSuperSecurityManager(self.getPortalObject()) portal_preferences = getToolByName(self, 'portal_preferences') preference_value = portal_preferences.getPreference(preference_id, default) setSecurityManager(original_security_manager) return preference_value
def applyProfile(portal, profileName, purge_old=None, ignore_dependencies=False, archive=None, blacklisted_steps=None): """Install an extension profile into the portal. The profile name should be a package name and a profile name, e.g. 'my.product:default'. """ from Acquisition import aq_parent from AccessControl import getSecurityManager from AccessControl.SecurityManagement import setSecurityManager sm = getSecurityManager() app = aq_parent(portal) z2.login(app['acl_users'], SITE_OWNER_NAME) try: setupTool = portal['portal_setup'] profileId = 'profile-{0}'.format(profileName) setupTool.runAllImportStepsFromProfile( profileId, purge_old=purge_old, ignore_dependencies=ignore_dependencies, archive=archive, blacklisted_steps=blacklisted_steps) portal.clearCurrentSkin() portal.setupCurrentSkin(portal.REQUEST) finally: setSecurityManager(sm)
def ImportSector(plone, options, filename): input = open(filename, "r") dom = lxml.objectify.parse(input) xml_sector = dom.getroot() country = GetCountry(plone, options) if not hasattr(xml_sector, "survey"): return sector = GetSector(country, xml_sector, options) if sector is None: raise Abort("No sector specified and no account information found.") # Login as the sector sup = UserProvider(sector) sectoruser = plone.acl_users.getUserById(sup.getUserId()) sm = getSecurityManager() try: newSecurityManager(None, sectoruser) name = options.name or six.text_type(xml_sector.survey.title.text) if hasattr(sector, name): raise Abort("There is already a survey named '%s'" % name) log.info("Importing survey '%s' with version '%s'", name, options.version) importer = SurveyImporter(sector) survey = importer(xml_sector, name, options.version) if options.publish: log.info("Publishing survey") publisher = publish.PublishSurvey(survey, None) publisher.publish() finally: setSecurityManager(sm)
def __call__(self, value, *args, **kwargs): context = getSite() portal_membership = getToolByName(context, "portal_membership") user_admin = portal_membership.getMemberById('admin') # stash the existing security manager so we can restore it old_security_manager = getSecurityManager() # create a new context, as the owner of the folder newSecurityManager(context,user_admin) portalGroup = getSite().portal_groups instance = kwargs.get('instance', None) req = kwargs['REQUEST'] form = req.form fields = ['Groups_view','Groups_edit','Groups_admin'] for item in fields: id_grupo = instance.UID() +'-'+item.split('_')[1] atual = instance.__getattribute__(item) news = form.get(item) alterado = set(atual) - set(news) for j in alterado: portalGroup.getGroupById(id_grupo).removeMember(j) # restore the original context setSecurityManager(old_security_manager)
def runLiveTest(test_list, verbosity=1, stream=None, request_server_url=None, **kw): from Products.ERP5Type.tests.runUnitTest import DebugTestResult from StringIO import StringIO # Add path of the TestTemplateItem folder of the instance path = kw.get('path', None) if path is not None and path not in sys.path: sys.path.append(path) product_test_list = [] import Products for product_path in Products.__path__: product_test_list.extend(glob(os.path.join(product_path, '*', 'tests'))) current_syspath = set(sys.path) global _request_server_url _request_server_url = request_server_url sys.path.extend(path for path in product_test_list if path not in current_syspath) TestRunner = unittest.TextTestRunner if ERP5TypeLiveTestCase not in ERP5TypeTestCase.__bases__: ERP5TypeTestCase.__bases__ = ERP5TypeLiveTestCase, if kw.get('debug', False): class DebugTextTestRunner(TestRunner): def _makeResult(self): result = super(DebugTextTestRunner, self)._makeResult() return DebugTestResult(result) TestRunner = DebugTextTestRunner run_only = kw.get('run_only', ()) filter_test_list = [re.compile(x).search for x in run_only] loader = ERP5TypeTestReLoader(filter_test_list) suite = loader.loadTestsFromNames(test_list) output = stream if stream is None: output = StringIO() def print_and_write(data): sys.stdout.write(data) sys.stdout.flush() return StringIO.write(output, data) output.write = print_and_write output.write("**Running Live Test:\n") ZopeTestCase._print = output.write # Test may login/logout with different users, so ensure that at the end the # original SecurityManager is restored from AccessControl.SecurityManagement import getSecurityManager, setSecurityManager sm = getSecurityManager() try: result = TestRunner(stream=output, verbosity=verbosity).run(suite) finally: setSecurityManager(sm)
def createDemo(self, wfaction=None): # Create tested content sm = getSecurityManager() self.loginAsPortalOwner() content = { "demo": { "type": 'ReferenceDataGridDemoType', "title": 'RDGF Demo' }, "doc": { "type": 'Document', "title": 'Test Document' }, "doc2": { "type": 'Document', "title": 'Test Document 2' }, } try: wf = self.portal.portal_workflow for cid, data in content.items(): makeContent(self.portal, portal_type=data['type'], id=cid) obj = getattr(self.portal, cid) obj.setTitle(data['title']) obj.reindexObject() if wfaction: wf.doActionFor(obj, wfaction) setattr(self, cid, obj) finally: setSecurityManager(sm)
def getExtensibleContent(self, request, name): # Be sure that html conversion is done, # as it is required to extract extensible content old_manager, user = self._forceIdentification(request) web_cache_kw = {'name': name, 'format': EMBEDDED_FORMAT} try: self._convert(format='html') view = _ViewEmulator().__of__(self) # If we have a conditional get, set status 304 and return # no content if _checkConditionalGET(view, web_cache_kw): return '' # call caching policy manager. _setCacheHeaders(view, web_cache_kw) mime, data = self.getConversion(format=EMBEDDED_FORMAT, filename=name) document = OFSFile(name, name, data, content_type=mime).__of__(self.aq_parent) except (NotConvertedError, ConversionError, KeyError): document = DocumentExtensibleTraversableMixin.getExtensibleContent( self, request, name) # restore original security context if there's a logged in user if user is not None: setSecurityManager(old_manager) return document
def changed_security(user=SpecialUsers.system): old_manager = getSecurityManager() newSecurityManager(getRequest(), user) yield setSecurityManager(old_manager)
def _notify(self, item, callback, name): if callable(callback): sm = getSecurityManager() try: user = sm.getUser() try: newSecurityManager(None, nobody) callback(item, self) except: # dont raise, just log path = self.getPhysicalPath() LOG.warning( '%s failed when calling %s in %s' % (name,callback, '/'.join(path)), exc_info=True ) finally: setSecurityManager(sm) else: err = '%s in %s attempted to call non-callable %s' path = self.getPhysicalPath() LOG.warning( err % (name, '/'.join(path), callback), exc_info=True )
def wrapped_func(*args, **kw): sm, site = getSecurityManager(), getSite() try: return func(*args, **kw) finally: setSecurityManager(sm) setSite(site)
def localBuild(self, activity_kw=()): """Activate builders for this delivery The generated activity will find all buildable business links for this delivery, and call related builders, which will select all simulation movements part of the same explanation(s) as the delivery. XXX: Consider moving it to SimulableMixin if it's useful for Subscription Items. """ # XXX: Previous implementation waited for expand activities of related # documents and even suggested to look at explanation tree, # instead of causalities. Is it required ? kw = {'priority': 3} kw.update(activity_kw) after_tag = kw.pop('after_tag', None) if isinstance(after_tag, basestring): after_tag = [after_tag] else: after_tag = list(after_tag) if after_tag else [] # Now that 'delivery' category relation are indexed in ZODB, this is the # only method that depends on built: tag (via _updateSimulation), which # is still required because builders only use catalog to find buildable # movements and we don't want to miss any for local building. after_tag.append('expand:' + self.getPath()) sm = getSecurityManager() newSecurityManager(None, nobody) try: unrestricted_apply(self.activate(after_tag=after_tag, **kw)._localBuild) finally: setSecurityManager(sm)
def localBuild(self, activity_kw=()): """Activate builders for this delivery The generated activity will find all buildable business links for this delivery, and call related builders, which will select all simulation movements part of the same explanation(s) as the delivery. XXX: Consider moving it to SimulableMixin if it's useful for Subscription Items. """ # XXX: Previous implementation waited for expand activities of related # documents and even suggested to look at explanation tree, # instead of causalities. Is it required ? kw = {'priority': 3} kw.update(activity_kw) after_tag = kw.pop('after_tag', None) if isinstance(after_tag, basestring): after_tag = [after_tag] else: after_tag = list(after_tag) if after_tag else [] after_tag.append('build:' + self.getPath()) sm = getSecurityManager() newSecurityManager(None, nobody) try: unrestricted_apply( self.activate(after_tag=after_tag, **kw)._localBuild) finally: setSecurityManager(sm)
def last_modifier(self): # Let's see if we have any last_modifier annotation raw_last_modifier = self._raw_last_modifier() if raw_last_modifier: return raw_last_modifier # If we are here: try with with history support if is available. history = queryMultiAdapter((self.context, self.request), interface=Interface, name=u"contenthistory") # Security is in the view definition. Here we act as an omnipotent user old_sm = getSecurityManager() tmp_user = UnrestrictedUser(old_sm.getUser().getId() or '', '', ['Manager'], '') newSecurityManager(None, tmp_user) try: if not history and sys.version_info < (2, 6): # We didn't found any history... is this a Plone 3? Let's try with the old history viewlet # To be sure of that let's do it only if we are using Python 2.4 # Please remove this abomination when Plone 3.3 compatibity will be dropped history = ContentHistoryViewlet(self.context, self.request, None, manager=None) history.update() if history: full_history = history.fullHistory() if full_history: return full_history[0].get('actorid') or full_history[0].get('actor').get('username') finally: setSecurityManager(old_sm)
def getFilteredActionDict(self, user_name=_MARKER): """ Returns menu items for a given user """ portal = self.getPortalObject() is_portal_manager = portal.portal_membership.checkPermission(\ Permissions.ManagePortal, self) downgrade_authenticated_user = user_name is not _MARKER and is_portal_manager if downgrade_authenticated_user: # downgrade to desired user original_security_manager = _setSuperSecurityManager(self, user_name) # call the method implementing it erp5_menu_dict = portal.portal_actions.listFilteredActionsFor(portal) if downgrade_authenticated_user: # restore original Security Manager setSecurityManager(original_security_manager) # Unlazyfy URLs and other lazy values so that it can be marshalled result = {} for key, action_list in erp5_menu_dict.items(): result[key] = map(lambda action:dict(action), action_list) return result
def assertUserHasWorklist(self, user_id, worklist_id, document_count): # type: (str, str, int) -> None self.portal.portal_workflow.refreshWorklistCache() self.portal.portal_caches.clearAllCache() sm = getSecurityManager() try: self._loginAsUser(user_id) global_action_list = [ x for x in self.portal.portal_workflow.listActions( object=self.portal) if x['category'] == 'global' ] worklist_action_list = [ x for x in global_action_list if x['worklist_id'] == worklist_id ] if not (worklist_action_list): self.fail("User %s does not have worklist %s.\nWorklists: %s" % (user_id, worklist_id, pformat(global_action_list))) worklist_action, = worklist_action_list self.assertEquals( document_count, worklist_action['count'], "User %s has %s documents in her %s worklist, not %s" % (user_id, worklist_action['count'], worklist_id, document_count)) finally: setSecurityManager(sm)
def getExtensibleContent(self, request, name): old_manager, user = self._forceIdentification(request) # Next get the document per name portal = self.getPortalObject() document = self.getDocumentValue(name=name, portal=portal) # restore original security context if there's a logged in user if user is not None: setSecurityManager(old_manager) if document is not None: document = aq_base( document.asContext( id= name, # Hide some properties to permit locating the original original_container=document.getParentValue(), original_id=document.getId(), editable_absolute_url=document.absolute_url())) return document.__of__(self) # no document found for current user, still such document may exists # in some cases user (like Anonymous) can not view document according to portal catalog # but we may ask him to login if such a document exists isAuthorizationForced = getattr(self, 'isAuthorizationForced', None) if isAuthorizationForced is not None and isAuthorizationForced(): if unrestricted_apply(self.getDocumentValue, (name, portal)) is not None: # force user to login as specified in Web Section raise Unauthorized
def elevated_privileges(): """Temporarily elevate current user's privileges. See http://docs.plone.org/develop/plone/security/permissions.html#bypassing-permission-checks for more documentation on this code. """ old_manager = getSecurityManager() try: # Clone the current user and assign a new role. # Note that the username (getId()) is left in exception # tracebacks in the error_log, # so it is an important thing to store. tmp_user = UnrestrictedUser( api.user.get_current().getId(), '', ('manage', ), '' ) # Wrap the user in the acquisition context of the portal tmp_user = tmp_user.__of__(api.portal.get().acl_users) newSecurityManager(getRequest(), tmp_user) yield finally: # Restore the old security manager setSecurityManager(old_manager)
def updateUsersPassword(): """ Met à jour les mots de passe des utilisateurs d'``acl_users`` de plone à partir des mots de passe de l'annuaire ``LDAP``. """ now = datetime.datetime.now() logger.info('Starting update passwords at ' + str(now)) portal = api.portal.get() sm = getSecurityManager() try: # go Admin, even in anymomous mode ! tmp_user = UnrestrictedUser( sm.getUser().getId(), '', ['Manager'], '') tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) users = api.user.get_users() portal = api.portal.get() pwds = portal.acl_users.source_users._user_passwords for user in users: uid = user.id try: iuem_user = getUserByUID(uid) pwds[uid] = iuem_user.pw except Exception: logger.info('Cannot update password for %s' % uid) transaction.commit() finally: # Restore the old security manager setSecurityManager(sm) now = datetime.datetime.now() logger.info('Update passwords finished at ' + str(now))
def quickInstallProduct(portal, productName, reinstall=False): """Install a product using the ``portal_quickinstaller`` tool. If ``reinstall`` is false and the product is already installed, do nothing. If ``reinstall`` is true, perform an explicit reinstall if the product is installed already. """ from Acquisition import aq_parent from AccessControl import getSecurityManager from AccessControl.SecurityManagement import setSecurityManager sm = getSecurityManager() app = aq_parent(portal) z2.login(app['acl_users'], SITE_OWNER_NAME) try: quickinstaller = portal['portal_quickinstaller'] if quickinstaller.isProductInstalled(productName): if reinstall: quickinstaller.reinstallProduct([productName]) else: quickinstaller.installProduct(productName) portal.clearCurrentSkin() portal.setupCurrentSkin(portal.REQUEST) finally: setSecurityManager(sm)
def handle_modified(self, content): fieldmanager = ILanguageIndependentFieldsManager(content) if not fieldmanager.has_independent_fields(): return sm = getSecurityManager() try: # Do we have permission to sync language independent fields? if self.bypass_security_checks(): # Clone the current user and assign a new editor role to # allow edition of all translated objects even if the # current user whould not have permission to do that. tmp_user = UnrestrictedUser(sm.getUser().getId(), '', [ 'Editor', ], '') # Wrap the user in the acquisition context of the portal # and finally switch the user to our new editor acl_users = getToolByName(content, 'acl_users') tmp_user = tmp_user.__of__(acl_users) newSecurityManager(None, tmp_user) # Copy over all language independent fields transmanager = ITranslationManager(content) for translation in self.get_all_translations(content): trans_obj = transmanager.get_translation(translation) if fieldmanager.copy_fields(trans_obj): self.reindex_translation(trans_obj) finally: # Restore the old security manager setSecurityManager(sm)
def applyProfile(portal, profileName, purge_old=None, ignore_dependencies=False, archive=None, blacklisted_steps=None): """Install an extension profile into the portal. The profile name should be a package name and a profile name, e.g. 'my.product:default'. """ from Acquisition import aq_parent from AccessControl import getSecurityManager from AccessControl.SecurityManagement import setSecurityManager sm = getSecurityManager() app = aq_parent(portal) z2.login(app['acl_users'], SITE_OWNER_NAME) try: setupTool = portal['portal_setup'] profileId = 'profile-%s' % (profileName, ) setupTool.runAllImportStepsFromProfile( profileId, purge_old=purge_old, ignore_dependencies=ignore_dependencies, archive=archive, blacklisted_steps=blacklisted_steps) portal.clearCurrentSkin() portal.setupCurrentSkin(portal.REQUEST) finally: setSecurityManager(sm)
def quickInstallProduct(portal, productName, reinstall=False): """Install a product using the ``portal_quickinstaller`` tool. If ``reinstall`` is false and the product is already installed, do nothing. If ``reinstall`` is true, perform an explicit reinstall if the product is installed already. """ from Acquisition import aq_parent from AccessControl import getSecurityManager from AccessControl.SecurityManagement import setSecurityManager sm = getSecurityManager() app = aq_parent(portal) z2.login(app['acl_users'], SITE_OWNER_NAME) try: quickinstaller = portal['portal_quickinstaller'] if quickinstaller.isProductInstalled(productName): if reinstall: quickinstaller.reinstallProducts([productName]) else: quickinstaller.installProduct(productName) portal.clearCurrentSkin() portal.setupCurrentSkin(portal.REQUEST) finally: setSecurityManager(sm)
def restrictMethodAsShadowUser(self, open_order=None, callable_object=None, argument_list=None, argument_dict=None): """ Restrict the security access of a method to the unaccessible shadow user associated to the current user. """ if argument_list is None: argument_list = [] if argument_dict is None: argument_dict = {} if open_order is None or callable_object is None: raise TypeError('open_order and callable_object cannot be None') relative_url = open_order.getRelativeUrl() if open_order.getPortalType() != 'Open Sale Order': raise Unauthorized("%s is not an Open Sale Order" % relative_url) else: # Check that open order is the validated one for the current user if open_order.getValidationState() != 'validated': raise Unauthorized('Open Sale Order %s is not validated.' % relative_url) acl_users = open_order.getPortalObject().acl_users # Switch to the shadow user temporarily, so that the behavior would not # change even if this method is invoked by random users. sm = getSecurityManager() newSecurityManager(None, acl_users.getUserById(open_order.getReference())) try: return callable_object(*argument_list, **argument_dict) finally: # Restore the original user. setSecurityManager(sm)
def failUnlessUserCanPassWorkflowTransition(self, user_id, transition, document): # type: (str, str, Base) -> None """Fails unless the user can pass the workflow transition on the document.""" sm = getSecurityManager() try: self._loginAsUser(user_id) user = getSecurityManager().getUser() valid_transition_list = [ ai['id'] for ai in self.workflow_tool.listActions(object=document) if ai['category'] == 'workflow' ] if transition not in valid_transition_list: # Build a comprehensive error message workflow_states_description = [] workflow_transitions_description = [] for wf in self.workflow_tool.getWorkflowValueListFor( document) or []: if wf.getId() == 'edit_workflow': continue if wf.__class__.__name__ in ( 'InteractionWorkflowDefinition', 'Interaction Workflow', ): continue for wf_transition in wf._getWorkflowStateOf( document).getDestinationValueList(): if wf_transition.getTriggerType( ) == TRIGGER_USER_ACTION: workflow_transitions_description.append( "%s%s[%s]\n\t\tExpression: %s\n\t\tPermissions: %s\n\t\tGroups: %s" % ( wf_transition.getReference() == transition and "* " or " ", wf_transition.getReference(), wf.getId(), wf_transition.getGuardExpression() or '', ', '.join(wf_transition. getGuardPermissionList()), ', '.join( wf_transition.getGuardGroupList()), )) workflow_states_description.append( "%s on %s" % (wf._getWorkflowStateOf( document, id_only=1), wf.getId())) document_description = "%s at %s (%s)" % ( document.getPortalType(), document.getPath(), ", ".join(workflow_states_description)) self.fail('User %s can NOT pass %s transition on %s.\n ' 'Roles: [%s]\n Available transitions:\n\t%s' % (user_id, transition, document_description, ", ".join(user.getRolesInContext(document)), "\n\t".join(workflow_transitions_description))) finally: setSecurityManager(sm)
def callAlarm(*args, **kwargs): sm = getSecurityManager() self.login() try: alarm.activeSense(params=kwargs) self.commit() finally: setSecurityManager(sm)
def runAs(user, call, *args, **kw): """Switch security manager (safely) to a manager user and back""" old_security_manager = getSecurityManager() newSecurityManager(None, user) try: return call(*args, **kw) finally: setSecurityManager(old_security_manager)
def trusted_fn(*args, **kwargs): try: value = fn(*args, **kwargs) except Unauthorized: orig_sec_mgr = getSecurityManager() newSecurityManager(None, system_user) value = fn(*args, **kwargs) setSecurityManager(orig_sec_mgr) return value
def getExpressConfigurationPreference(self, preference_id, default=None): """ Get Express configuration preference """ original_security_manager = _setSuperSecurityManager( self.getPortalObject()) portal_preferences = getToolByName(self, 'portal_preferences') preference_value = portal_preferences.getPreference( preference_id, default) setSecurityManager(original_security_manager) return preference_value
def process_timer(self, tick, interval, prev="", next=""): if timerservice_lock.acquire(0): try: try: notify_list = aq_base(self)._v_notify_list except AttributeError: current_node = self.getCurrentNode() self._v_notify_list = notify_list = [ x.getId() for x in self.objectValues() if x.isEnabled() and current_node in x.getNodeList() ] update_state_dict = {} original_security_manager = getSecurityManager() for notify_id in notify_list: notify = self._getOb(notify_id) newSecurityManager(None, notify.getWrappedOwner()) try: inode_path = notify.getInodePath() if inode_path: path = notify.getPath() state = inotify_state_dict.get(path, {}) new_state = {} for inode_path in glob.glob(inode_path): for name in os.listdir(inode_path): p = os.path.join(inode_path, name) try: s = os.lstat(p) except OSError, e: if e.errno != errno.ENOENT: raise else: new_state[p] = s.st_mtime, s.st_size if new_state != state: update_state_dict[path] = new_state events = [{ 'path': p, 'mask': IN_DELETE } for p in set(state).difference(new_state)] for p, m in new_state.iteritems(): if p in state: if m == state[p]: continue mask = IN_MODIFY else: mask = IN_CREATE events.append({'path': p, 'mask': mask}) getattr(notify, notify.getSenseMethodId())(events) finally: setSecurityManager(original_security_manager) if update_state_dict: TransactionalResource( tpc_finish=lambda txn: inotify_state_dict.update( update_state_dict)) finally: timerservice_lock.release()