Example #1
0
 def changeUser(self, user_id):
   """
     Change the current user to user_id
   """
   user_folder = self.getPortal().acl_users
   user = user_folder.getUserById(user_id).__of__(user_folder)
   newSecurityManager(None, user)
Example #2
0
 def login(self):
   uf = self.portal.acl_users
   uf._doAddUser('daniele', 'myPassword', ['Manager'], [])
   uf._doAddUser('ERP5TypeTestCase', '', ['Manager'], [])
   uf._doAddUser('syncml', '', ['Manager'], [])
   user = uf.getUserById('daniele').__of__(uf)
   newSecurityManager(None, user)
Example #3
0
    def test_CopyPasteSetsOwnership(self):
        # Copy/pasting a File should set new ownership including local roles
        from OFS.Folder import Folder

        acl_users = self.acl_users
        folder1 = self.site._setObject('folder1', Folder('folder1'))
        folder2 = self.site._setObject('folder2', Folder('folder2'))

        newSecurityManager(None, acl_users.user_foo)
        content = self._initContent(folder1, 'content')
        content.manage_setLocalRoles(acl_users.user_foo.getId(), ['Owner'])

        newSecurityManager(None, acl_users.all_powerful_Oz)
        cb = folder1.manage_copyObjects(['content'])
        folder2.manage_pasteObjects(cb)

        # Now test executable ownership and "owner" local role
        # "member" should have both.
        moved = folder2._getOb('content')
        self.assertEqual(aq_base(moved.getOwner()),
                         aq_base(acl_users.all_powerful_Oz))

        local_roles = moved.get_local_roles()
        self.assertEqual(len(local_roles), 1)
        userid, roles = local_roles[0]
        self.assertEqual(userid, acl_users.all_powerful_Oz.getId())
        self.assertEqual(len(roles), 1)
        self.assertEqual(roles[0], 'Owner')
Example #4
0
  def stepAuthorImportFile(self, sequence=None, sequence_list=None, **kw):
    # create some regions
    region = self.portal.portal_categories.region
    europe = region.newContent(portal_type='Category',
                      title='Europe',
                      id='europe')
    europe.newContent(portal_type='Category',
                      title='France',
                      id='france')

    user_name = 'author'
    user_folder = self.portal.acl_users
    user_folder._doAddUser(user_name, '', ['Author', 'Member'], [])
    user = user_folder.getUserById(user_name).__of__(user_folder)
    newSecurityManager(None, user)

    f = makeFileUpload('import_data_with_categories.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.function'},
    { 'listbox_key': '005',
      'portal_type_property_list':'Person.region'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)
def checkin_documents_for_user(portal, options):
    """Attempts to check in all documents checked out by a particular user.
    """
    username = options.user

    # Assume security context of user
    user = portal.acl_users.getUser(username)
    user = user.__of__(portal.acl_users)
    newSecurityManager(portal, user)

    catalog = getToolByName(portal, 'portal_catalog')
    docs = catalog(portal_type='opengever.document.document')
    checked_out_docs = [b.getObject() for b in docs if b.checked_out == username]

    for obj in checked_out_docs:
        manager = getMultiAdapter((obj, obj.REQUEST), ICheckinCheckoutManager)
        if not manager.is_checkin_allowed():
            print "WARNING: Checkin not allowed for document %s" % obj.absolute_url()
            print checkin_not_allowed_reason(obj)
        else:
            if not options.dryrun:
                manager.checkin(comment=options.comment)
                print "Checked in document %s" % obj.absolute_url()
            else:
                print "Would checkin document %s" % obj.absolute_url()

    if not options.dryrun:
        transaction.commit()
Example #6
0
    def test_isConstructionAllowed_w_Role( self ):

        ti, folder = self._makeStuff()

        newSecurityManager( None
                          , UserWithRoles( 'FooAdder' ).__of__( folder ) )
        self.failUnless( ti.isConstructionAllowed( folder ) )
Example #7
0
 def test_constructInstance_private(self):
     ti, folder = self._makeStuff()
     newSecurityManager(None,
                        UserWithRoles('NotAFooAdder').__of__(folder))
     ti._constructInstance(folder, 'foo')
     foo = folder._getOb('foo')
     self.assertEqual(foo.id, 'foo')
def main(app, id, title, dbauser, dbuser, dbname, dbserver, dbport):
    _policy=PermissiveSecurityPolicy()
    _oldpolicy=setSecurityPolicy(_policy)
    newSecurityManager(None, EvenMoreOmnipotentUser().__of__(app.acl_users))
    app = makerequest(app)

    # Add Rhaptos Site
    factory = app.manage_addProduct['RhaptosSite']
    factory.manage_addRhaptosSite(id,
        title=title, description='',
        dbauser=dbauser,
        dbapass=None,
        dbuser=dbuser,
        dbpass=None,
        dbname=dbname,
        dbserver=dbserver,
        dbport=dbport and int(dbport) or None)

    # Add Virtual Host Entry
    app.virtual_hosting.set_map('http://*.cnx.rice.edu/ /'+id+'\nhttp://localhost/ /'+id)

    # Apply cnx.org styles
    site = getattr(app, id)
    site.portal_setup.setImportContext(
        'profile-Products.CNXPloneSite:default')
    site.portal_setup.manage_importSelectedSteps(
        ['cnx_install'],
        True,  # run_dependencies
        app.REQUEST.RESPONSE)

    transaction.commit()
Example #9
0
    def test_constructContent(self):
        site = self.site
        acl_users = self.acl_users
        ttool = self.ttool
        setSecurityPolicy(self._oldPolicy)
        newSecurityManager(None, acl_users.all_powerful_Oz)
        self.site._owner = (['acl_users'], 'all_powerful_Oz')
        sti_baz = STI('Baz',
                      permission='Add portal content',
                      constructor_path='addBaz')
        ttool._setObject('Baz', sti_baz)
        ttool._setObject( 'addBaz',  PythonScript('addBaz') )
        s = ttool.addBaz
        s.write(STI_SCRIPT)

        f = site._setObject( 'folder', PortalFolder(id='folder') )
        f.manage_addProduct = { 'FooProduct' : DummyFactory(f) }
        f._owner = (['acl_users'], 'user_foo')
        self.assertEqual( f.getOwner(), acl_users.user_foo )

        ttool.constructContent('Dummy Content', container=f, id='page1')
        try:
            ttool.constructContent('Baz', container=f, id='page2')
        except Unauthorized:
            self.fail('CMF Collector issue #165 (Ownership bug): '
                      'Unauthorized raised' )
    def test_listActionInformationActions(self):
        # Check that listFilteredActionsFor works for objects that return
        # ActionInformation objects
        tool = self.tool
        act = 'string:${folder_url}/folder_contents'
        tool._actions = (
              ActionInformation(id='folderContents',
                                title='Folder contents',
                                action=Expression(text=act),
                                icon_expr=Expression(text='string:'
                                                     '${folder_url}/icon.gif'),
                                condition=Expression(text='python: '
                                                     'folder is not object'),
                                permissions=('List folder contents',),
                                category='folder',
                                link_target='_top',
                                visible=1),)

        newSecurityManager(None, OmnipotentUser().__of__(self.app.acl_users))
        self.assertEqual(tool.listFilteredActionsFor(self.app.foo),
                         {'workflow': [],
                          'user': [],
                          'object': [],
                          'folder': [{'id': 'folderContents',
                                      'url': 'http://nohost/folder_contents',
                                      'icon': 'http://nohost/icon.gif',
                                      'title': 'Folder contents',
                                      'description': '',
                                      'visible': True,
                                      'available': True,
                                      'allowed': True,
                                      'category': 'folder',
                                      'link_target': '_top'}],
                          'global': []})
Example #11
0
 def setUp(self):
     transaction.begin()
     self._policy = PermissiveSecurityPolicy()
     self._oldPolicy = setSecurityPolicy(self._policy)
     self.connection = Zope2.DB.open()
     self.root =  self.connection.root()[ 'Application' ]
     newSecurityManager( None, AnonymousUser().__of__( self.root ) )
Example #12
0
 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
             )
Example #13
0
    def get_filetype_info(self, filetype):
        current_user = getSecurityManager().getUser()
        newSecurityManager(None, UnrestrictedUser('andago', '', ['Manager'], []))
        ret =  self.decorateBrains(self.portal_catalog(filetype=filetype, portal_type='BoardDocument', Language='es'))

        newSecurityManager(None, current_user)
        return ret
Example #14
0
 def getOrder(self, context, request):
     """ This turns a little complex, because the call from BulkSMS is 
         unauthenticated in the plone sense. Thus this code essentially runs
         as 'Anonymous'. We do an unrestrictedSearchResults to get the brain.
         Then we switch users to the owner of that object. This means we
         never give the user more rights on this object than they should
         have.
     """
     verification_code = request.get('message')
     if not verification_code:
         return None
   
     verification_code = verification_code.strip()
     pc = getToolByName(self.context, 'order_catalog')
     query = {'portal_type': 'emas.app.order',
      'review_state': 'ordered',
              'verification_code': verification_code}
     try:
         brains = pc.unrestrictedSearchResults(query)
     except UnicodeDecodeError:
         return None
     if not brains or len(brains) < 1:
         LOGGER.debug(
             'Could not find order with verification code:'
             '%s' % verification_code)
         return None
     brain = brains[0]
     order = brain._unrestrictedGetObject()
     pmt = getToolByName(self.context, 'portal_membership')
     user = pmt.getMemberById(order.userid)
     if user is not None:
         newSecurityManager(request, user)
         return order
     return None
Example #15
0
    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)
Example #16
0
    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)
Example #17
0
    def test_overrideDiscussionFor(self):
        acl_users = self.site._setObject('acl_users', DummyUserFolder())
        newSecurityManager(None, acl_users.all_powerful_Oz)
        dtool = self.dtool
        foo = self.site._setObject( 'foo', DummyFolder() )
        baz = foo._setObject( 'baz', DummyFolder() )

        dtool.overrideDiscussionFor(foo, 1)
        self.failUnless( hasattr(foo.aq_base, 'allow_discussion') )
        try:
            dtool.overrideDiscussionFor(baz, None)
        except KeyError:
            self.fail('CMF Collector issue #201 (acquisition bug): '
                      'KeyError raised')
        dtool.overrideDiscussionFor(foo, None)
        self.failIf( hasattr(foo.aq_base, 'allow_discussion') )

        # https://bugs.launchpad.net/zope-cmf/+bug/162532: Don't break
        # if allow_discussion only exists at the class level
        class DummyContent:
            allow_discussion = False
            def getId(self): return 'dummy'

        dummy = DummyContent()
        try:
            dtool.overrideDiscussionFor(dummy, None)
        except AttributeError:
            self.fail('Launchpad issue 162532: AttributeError raised')
Example #18
0
def proxyMethodHandler(self, kw):
    """Dummy proxyMethodHandler"""
    # login as super user
    newSecurityManager(self, self.getPortalObject().acl_users.getUserById(ERP5Security.SUPER_USER))
    data = getattr(self, kw["method_id"])(**kw["method_kw"])
    response = GeneratorCall(data=data)
    return response.dump()
Example #19
0
    def setUp(self):
        self._trap_warning_output()
        transaction.begin()

        app = self.app = makerequest(Zope2.app())
        # Log in as a god :-)
        newSecurityManager( None, UnrestrictedUser('god', 'god', ['Manager'], '') )

        app.manage_addProduct['CMFDefault'].manage_addCMFSite('CalendarTest')

        self.Site = app.CalendarTest

        manage_addExternalMethod(app.CalendarTest,
                                 id='install_events',
                                 title="Install Events",
                                 module="CMFCalendar.Install",
                                 function="install")

        ExMethod = app.restrictedTraverse('/CalendarTest/install_events')
        ExMethod()
        self.Tool = app.CalendarTest.portal_calendar

        self.Site.clearCurrentSkin()
        self.Site.setupCurrentSkin(app.REQUEST)

        # sessioning setup
        if getattr(app, 'temp_folder', None) is None:
            temp_folder = MountedTemporaryFolder('temp_folder')
            app._setObject('temp_folder', temp_folder)
        if getattr(app.temp_folder, 'session_data', None) is None:
            session_data = TransientObjectContainer('session_data')
            app.temp_folder._setObject('session_data', session_data)
        app.REQUEST.set_lazy( 'SESSION',
                              app.session_data_manager.getSessionData )
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)
Example #21
0
 def login(self) :
   """sets the security manager"""
   uf = self.getPortal().acl_users
   uf._doAddUser('alex', '', ['Member', 'Assignee', 'Assignor',
                              'Auditor', 'Author', 'Manager'], [])
   user = uf.getUserById('alex').__of__(uf)
   newSecurityManager(None, user)
Example #22
0
    def testUpgradeAllProposed(self):
        request = self.app.REQUEST
        oldsite = getattr(self.app, self._SITE_ID)
        stool = oldsite.portal_setup
        profile_id = 'Products.CMFDefault:default'
        upgrades = []
        for upgrade_info in stool.listUpgrades(profile_id):
            if isinstance(upgrade_info, list):
                for info in upgrade_info:
                    if info['proposed']:
                        upgrades.append(info['id'])
                continue
            if upgrade_info['proposed']:
                upgrades.append(upgrade_info['id'])

        request.form['profile_id'] = profile_id
        request.form['upgrades'] = upgrades
        stool.manage_doUpgrades(request)

        self.assertEqual(stool.getLastVersionForProfile(profile_id),
                         ('2', '2'))

        newSecurityManager(None, UnrestrictedUser('god', '', ['Manager'], ''))
        setSite(self.app.site)
        expected_export = self.app.site.portal_setup.runAllExportSteps()
        setSite(oldsite)
        upgraded_export = stool.runAllExportSteps()

        expected = TarballImportContext(stool, expected_export['tarball'])
        upgraded = TarballImportContext(stool, upgraded_export['tarball'])
        diff = stool.compareConfigurations(upgraded, expected)
        self.assertEqual(diff, '', diff)
Example #23
0
 def test_constructInstance_private(self):
     from AccessControl.SecurityManagement import newSecurityManager
     from Products.CMFCore.tests.base.security import UserWithRoles
     newSecurityManager(None, UserWithRoles('NotAFooAdder').__of__(self.f))
     self.ti._constructInstance(self.f, 'foo')
     foo = self.f._getOb('foo')
     self.assertEqual(foo.id, 'foo')
Example #24
0
    def test_constructContent_simple_STI(self):
        from AccessControl import Unauthorized
        from AccessControl.SecurityManagement import newSecurityManager
        from AccessControl.SecurityManager import setSecurityPolicy
        from Products.CMFCore.PortalFolder import PortalFolder
        from Products.CMFCore.TypesTool \
                import ScriptableTypeInformation as STI
        from Products.CMFCore.tests.base.dummy import DummyFactoryDispatcher
        from Products.CMFCore.tests.base.tidata import STI_SCRIPT
        from Products.PythonScripts.PythonScript import PythonScript
        site = self._makeSite().__of__(self.root)
        acl_users = site.acl_users
        setSecurityPolicy(self._oldPolicy)
        newSecurityManager(None, acl_users.all_powerful_Oz)
        tool = self._makeOne().__of__(site)
        sti_baz = STI('Baz',
                      permission='Add portal content',
                      constructor_path='addBaz')
        tool._setObject('Baz', sti_baz)
        script = PythonScript('addBaz')
        script.write(STI_SCRIPT)
        tool._setObject('addBaz',  script)
        folder = site._setObject( 'folder', PortalFolder(id='folder') )
        folder.manage_addProduct = {'FooProduct':
                                        DummyFactoryDispatcher(folder) }
        folder._owner = (['acl_users'], 'user_foo')
        self.assertEqual( folder.getOwner(), acl_users.user_foo )

        try:
            tool.constructContent('Baz', container=folder, id='page2')
        except Unauthorized:
            self.fail('CMF Collector issue #165 (Ownership bug): '
                      'Unauthorized raised' )

        self.assertEqual(folder.page2.portal_type, 'Baz')
Example #25
0
 def test_constructInstance_wo_Roles(self):
     from AccessControl.SecurityManagement import newSecurityManager
     from AccessControl.unauthorized import Unauthorized
     from Products.CMFCore.tests.base.security import UserWithRoles
     newSecurityManager(None, UserWithRoles('FooViewer').__of__(self.f))
     self.assertRaises(Unauthorized,
                       self.ti.constructInstance, self.f, 'foo')
Example #26
0
  def test_BasicAuthenticateDesactivated(self):
    """Make sure Unauthorized error does not lead to Basic auth popup in browser"""
    portal = self.getPortal()
    # Create user account with very long login name
    login_name = 'foo_login_name'
    password = '******'
    acl_users = portal.acl_users
    acl_users._doAddUser(login_name, password, ['Member'], [])
    user = acl_users.getUserById(login_name).__of__(acl_users)
    # Login as the above user
    newSecurityManager(None, user)
    self.auth = '%s:%s' % (login_name, password)
    self.commit()
    self.tic()

    api_scheme, api_netloc, api_path, api_query, \
      api_fragment = urlparse.urlsplit(self.portal.absolute_url())

    connection = httplib.HTTPConnection(api_netloc)
    connection.request(
      method='GET',
      url='%s/Person_getPrimaryGroup' % \
          self.portal.absolute_url(),
      headers={
       'Authorization': 'Basic %s' % \
         base64.b64encode(self.auth)
      }
    )
    response = connection.getresponse()
    self.assertEqual(response.status, 401)
    self.assertEqual(response.getheader('WWW-Authenticate'), None)
Example #27
0
    def __call__(self, *args):
        """
        """
        plominoContext = self
        try:
            if self.run_as == "OWNER":

                # Remember the current user
                member = self.getCurrentMember()
                if member.__class__.__name__ == "SpecialUser":
                    user = member
                else:
                    user = member.getUser()

                # Switch to the agent's owner
                owner = self.getOwner()
                newSecurityManager(None, owner)

            result = self.runFormulaScript(
                "agent_" + self.id,
                plominoContext,
                self.content,
                True,
                *args
            )

            # Switch back to the original user
            if self.run_as == "OWNER":
                newSecurityManager(None, user)

        except PlominoScriptException, e:
            e.reportError('Agent failed')
            result = None
Example #28
0
 def setUp(self):
     from AccessControl.SecurityManagement import newSecurityManager
     from Products.CMFCore.tests.base.dummy import DummyFolder
     from Products.CMFCore.tests.base.security import UserWithRoles
     self.f = DummyFolder(fake_product=1)
     self.ti = self._makeOne('Foo', product='FooProduct', factory='addFoo')
     newSecurityManager(None, UserWithRoles('FooAdder').__of__(self.f))
Example #29
0
  def test_catalog_with_very_long_login_name(self, quiet=quiet, run=run_all_test):
    """Make sure that user with very long login name can find his document by catalog"""
    portal = self.getPortal()
    # Create user account with very long login name
    login_name = 'very_very_looooooooooooooooooooooooooooooooooooooooooooooooooooo' + \
    'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_login_name'
    password = '******' + \
    'ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'
    acl_users = portal.acl_users
    acl_users._doAddUser(login_name, password, ['Member'], [])
    user = acl_users.getUserById(login_name).__of__(acl_users)
    # Login as the above user
    newSecurityManager(None, user)
    self.auth = '%s:%s' % (login_name, password)
    self.commit()

    # Create preference
    portal.portal_preferences.newContent('Preference', title='My Test Preference')

    self.tic()

    self.assertEqual(
      len(portal.portal_catalog(portal_type='Preference',
                                title='My Test Preference')),
      1)
    response = self.publish(self.portal_id, self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
def onDiscussionItemAddedEvent(object,event):
    from AccessControl.SecurityManagement import newSecurityManager
    from AccessControl import getSecurityManager
    import transaction

    contextuser = getSecurityManager().getUser()

    discussion_item = object
    discussed_item = discussion_item
    while discussed_item.meta_type == discussion_item.meta_type:
        discussed_item = discussed_item.aq_inner.aq_parent.aq_parent


    modifiedat = None
    try:
        modifiedat = discussion_item.created()
    except AttributeError:
        modifiedat = None

    if modifiedat <> None:
        try:
            onObjectModification(discussed_item,last_change_action_comment,modifiedat)
            onObjectModification(discussion_item,last_change_action_add,modifiedat)
            discussed_item.reindexObject()
            discussion_item.reindexObject()
        except:
            currentOwner = discussed_item.getOwner()
            newSecurityManager(None,currentOwner)
            onObjectModification(discussed_item,last_change_action_comment,modifiedat)
            onObjectModification(discussion_item,last_change_action_add,modifiedat)
            discussed_item.reindexObject()
            discussion_item.reindexObject()
            newSecurityManager(None,contextuser)
Example #31
0
from AccessControl import getSecurityManager
from AccessControl.User import UnrestrictedUser
from AccessControl.SecurityManagement import newSecurityManager
from bika.lims import api
import csv

portal = api.get_portal()
me = UnrestrictedUser(getSecurityManager().getUser().getUserName(), '',
                      ['LabManager'], '')
me = me.__of__(portal.acl_users)
newSecurityManager(None, me)

clients = map(api.get_object, api.search({'portal_type': 'Client'}))
data = []
cols = [
    'Status',
    'NAL Number',
    'Client ID',
    'Email Address',
    'Phone',
    'MBG Grower Number',
    'TrueBlue Grower Number',
    'Grower List',
    'Country',
    'State',
    'District',
    'City',
    'Zip',
    'Address',
]
for i in clients:
Example #32
0
    def test_isConstructionAllowed_wo_Role(self):

        ti, folder = self._makeStuff()

        newSecurityManager(None, UserWithRoles('FooViewer').__of__(folder))
Example #33
0
    def test_isConstructionAllowed_w_Role(self):

        ti, folder = self._makeStuff()

        newSecurityManager(None, UserWithRoles('FooAdder').__of__(folder))
        self.failUnless(ti.isConstructionAllowed(folder))
Example #34
0
    def test_isConstructionAllowed_for_Omnipotent(self):

        ti, folder = self._makeStuff()
        newSecurityManager(None, OmnipotentUser().__of__(folder))
        self.failUnless(ti.isConstructionAllowed(folder))
Example #35
0
    def activeSense(self, fixit=0, params=None):
        """
    This method launches the sensing process as activities.
    It is intended to launch a very long process made
    of many activities. It returns nothing since the results
    are collected in an active process.

    The result of the sensing process can be obtained by invoking
    the sense method or by requesting a report.
    """
        portal_membership = self.getPortalObject().portal_membership
        if fixit or not self.getEnabled():
            checkPermission = portal_membership.checkPermission
            if not checkPermission(Permissions.ManagePortal, self):
                raise Unauthorized(
                    'fixing problems or activating a disabled alarm is not allowed'
                )

        # Use UnrestrictedMethod, so that the behaviour would not
        # change even if this method is invoked by random users.
        @UnrestrictedMethod
        def _activeSense():
            # Set the next date at which this method should be invoked
            self.setNextAlarmDate()

            # Find the active sensing method and invoke it
            # as an activity so that we can benefit from
            # distribution of alarm processing as soon as possible
            method_id = self.getActiveSenseMethodId()
            if method_id not in (None, ''):
                # A tag is provided as a parameter in order to be
                # able to notify the user after all processes are ended
                # We do some inspection to keep compatibility
                # (because fixit and tag were not set previously)
                tag = self.__getTag(True)
                method = getattr(self, method_id)
                func_code = method.func_code
                try:
                    has_kw = func_code.co_flags & CO_VARKEYWORDS
                except AttributeError:
                    # XXX guess presence of *args and **kw
                    name_list = func_code.co_varnames[func_code.co_argcount:]
                    has_args = bool(name_list and name_list[0] == 'args')
                    has_kw = bool(
                        len(name_list) > has_args
                        and name_list[has_args] == 'kw')
                name_list = func_code.co_varnames[:func_code.co_argcount]
                if 'params' in name_list or has_kw:
                    # New New API
                    getattr(self.activate(tag=tag), method_id)(fixit=fixit,
                                                               tag=tag,
                                                               params=params)
                elif 'fixit' in name_list:
                    # New API - also if variable number of named parameters
                    getattr(self.activate(tag=tag), method_id)(fixit=fixit,
                                                               tag=tag)
                else:
                    # Old API
                    getattr(self.activate(tag=tag), method_id)()
                if self.isAlarmNotificationMode():
                    self.activate(after_tag=tag).notify(include_active=True,
                                                        params=params)

        # switch to nobody temporarily so that unrestricted _activeSense
        # is always invoked by system user.
        sm = getSecurityManager()
        newSecurityManager(None, nobody)
        try:
            _activeSense()
        finally:
            # Restore the original user.
            setSecurityManager(sm)
Example #36
0
def validate_user(request, user):
    newSecurityManager(request, user)
 def login(self):
   uf = self.portal.acl_users
   uf._doAddUser('vincent', '', ['Manager'], [])
   user = uf.getUserById('vincent').__of__(uf)
   newSecurityManager(None, user)
Example #38
0
 def login(self, quiet=0, run=run_all_test):
     uf = self.getPortal().acl_users
     uf._doAddUser(self.manager_username, self.manager_password,
                   ['Manager'], [])
     user = uf.getUserById(self.manager_username).__of__(uf)
     newSecurityManager(None, user)
Example #39
0
    def test_contentPaste(self):
        #
        #   Does copy / paste work?
        #
        acl_users = self.site._setObject('acl_users', DummyUserFolder())
        newSecurityManager(None, acl_users.all_powerful_Oz)
        ctool = DummyCatalogTool()
        ttool = TypesTool()
        fti = FTIDATA_DUMMY[0].copy()
        ttool._setObject('Dummy Content', FTI(**fti))
        sub1 = self._makeOne('sub1')
        sub2 = self._makeOne('sub2')
        sub3 = self._makeOne('sub3')
        self.assertEqual(len(ctool), 0)
        sm = getSiteManager()
        sm.registerUtility(ctool, ICatalogTool)
        sm.registerUtility(ttool, ITypesTool)

        sub1._setObject('dummy', DummyContent('dummy', catalog=1))
        self.assertTrue('dummy' in sub1.objectIds())
        self.assertTrue('dummy' in sub1.contentIds())
        self.assertFalse('dummy' in sub2.objectIds())
        self.assertFalse('dummy' in sub2.contentIds())
        self.assertFalse('dummy' in sub3.objectIds())
        self.assertFalse('dummy' in sub3.contentIds())
        self.assertTrue(has_path(ctool, '/bar/site/sub1/dummy'))
        self.assertFalse(has_path(ctool, '/bar/site/sub2/dummy'))
        self.assertFalse(has_path(ctool, '/bar/site/sub3/dummy'))

        cookie = sub1.manage_copyObjects(ids=('dummy', ))
        # Waaa! force sub2 to allow paste of Dummy object.
        sub2.all_meta_types = []
        sub2.all_meta_types.extend(sub2.all_meta_types)
        sub2.all_meta_types.extend(extra_meta_types())
        sub2.manage_pasteObjects(cookie)
        self.assertTrue('dummy' in sub1.objectIds())
        self.assertTrue('dummy' in sub1.contentIds())
        self.assertTrue('dummy' in sub2.objectIds())
        self.assertTrue('dummy' in sub2.contentIds())
        self.assertFalse('dummy' in sub3.objectIds())
        self.assertFalse('dummy' in sub3.contentIds())
        self.assertTrue(has_path(ctool, '/bar/site/sub1/dummy'))
        self.assertTrue(has_path(ctool, '/bar/site/sub2/dummy'))
        self.assertFalse(has_path(ctool, '/bar/site/sub3/dummy'))

        transaction.savepoint(optimistic=True)
        cookie = sub1.manage_cutObjects(ids=('dummy', ))
        # Waaa! force sub2 to allow paste of Dummy object.
        sub3.all_meta_types = []
        sub3.all_meta_types.extend(sub3.all_meta_types)
        sub3.all_meta_types.extend(extra_meta_types())
        sub3.manage_pasteObjects(cookie)
        self.assertFalse('dummy' in sub1.objectIds())
        self.assertFalse('dummy' in sub1.contentIds())
        self.assertTrue('dummy' in sub2.objectIds())
        self.assertTrue('dummy' in sub2.contentIds())
        self.assertTrue('dummy' in sub3.objectIds())
        self.assertTrue('dummy' in sub3.contentIds())
        self.assertFalse(has_path(ctool, '/bar/site/sub1/dummy'))
        self.assertTrue(has_path(ctool, '/bar/site/sub2/dummy'))
        self.assertTrue(has_path(ctool, '/bar/site/sub3/dummy'))
Example #40
0
 def loginAsUser(self, username):
     uf = self.portal.acl_users
     user = uf.getUser(username).__of__(uf)
     uf.zodb_roles.assignRoleToPrincipal('Manager', user.getId())
     newSecurityManager(None, user)
Example #41
0
 def login(self, name):
     user = self.uf.getUserById(name)
     user = user.__of__(self.uf)
     newSecurityManager(None, user)
Example #42
0
 def loginAsUser(self, user_id):
     """Login with a given user_id """
     uf = self.getPortal().acl_users
     user = uf.getUserById(user_id).__of__(uf)
     return newSecurityManager(None, user)
Example #43
0
 def test_isConstructionAllowed_for_Omnipotent(self):
     from AccessControl.SecurityManagement import newSecurityManager
     from Products.CMFCore.tests.base.security import OmnipotentUser
     newSecurityManager(None, OmnipotentUser().__of__(self.f))
     self.failUnless(self.ti.isConstructionAllowed(self.f))
Example #44
0
 def test_setObject_set_owner_with_no_user( self ):
     om = self._makeOne()
     newSecurityManager( None, None )
     si = SimpleItem( 'no_user' )
     om._setObject( 'no_user', si )
     self.assertEqual( si.__ac_local_roles__, None )
Example #45
0
 def changeToAnonymous(self):
     """
 Change the current user to Anonymous
 """
     newSecurityManager(None, SpecialUsers.nobody)
Example #46
0
 def test_isConstructionAllowed_wo_Role(self):
     from AccessControl.SecurityManagement import newSecurityManager
     from Products.CMFCore.tests.base.security import UserWithRoles
     newSecurityManager(None, UserWithRoles('FooViewer').__of__(self.f))
     self.failIf(self.ti.isConstructionAllowed(self.f))
Example #47
0
 def login(self):
     uf = self.getPortal().acl_users
     uf._doAddUser(self.username, '', ['Manager'], [])
     user = uf.getUserById(self.username).__of__(uf)
     newSecurityManager(None, user)
Example #48
0
 def login(self):
   uf = self.getPortal().acl_users
   uf._doAddUser('admin', '', ['Manager'], [])
   uf._doAddUser('ERP5TypeTestCase', '', ['Manager'], [])
   user = uf.getUserById('admin').__of__(uf)
   newSecurityManager(None, user)
Example #49
0
 def loginAsPortalOwner(self):
     '''Use if you need to manipulate an article as member.'''
     uf = self.app.acl_users
     user = uf.getUserById(portal_owner).__of__(uf)
     newSecurityManager(None, user)
Example #50
0
 def setUp(self):
     newSecurityManager(None, None)
Example #51
0
def startup():
    from App.PersistentExtra import patchPersistent
    import Globals  # to set / fetch data
    patchPersistent()

    global app

    # Import products
    OFS.Application.import_products()

    configuration = getConfiguration()

    # Open the database
    dbtab = configuration.dbtab
    try:
        # Try to use custom storage
        try:
            m = imp.find_module('custom_zodb', [configuration.testinghome])
        except:
            m = imp.find_module('custom_zodb', [configuration.instancehome])
    except Exception:
        # if there is no custom_zodb, use the config file specified databases
        DB = dbtab.getDatabase('/', is_root=1)
    else:
        m = imp.load_module('Zope2.custom_zodb', m[0], m[1], m[2])
        sys.modules['Zope2.custom_zodb'] = m

        # Get the database and join it to the dbtab multidatabase
        # FIXME: this uses internal datastructures of dbtab
        databases = getattr(dbtab, 'databases', {})
        if hasattr(m, 'DB'):
            DB = m.DB
            databases.update(getattr(DB, 'databases', {}))
            DB.databases = databases
        else:
            DB = ZODB.DB(m.Storage, databases=databases)

    notify(DatabaseOpened(DB))

    Globals.BobobaseName = DB.getName()

    if DB.getActivityMonitor() is None:
        from ZODB.ActivityMonitor import ActivityMonitor
        DB.setActivityMonitor(ActivityMonitor())

    Globals.DB = DB
    Zope2.DB = DB

    # Hook for providing multiple transaction object manager undo support:
    Globals.UndoManager = DB

    Globals.opened.append(DB)
    import ClassFactory
    DB.classFactory = ClassFactory.ClassFactory

    # "Log on" as system user
    newSecurityManager(None, AccessControl.User.system)

    # Set up the CA
    load_zcml()

    # Set up the "app" object that automagically opens
    # connections
    app = App.ZApplication.ZApplicationWrapper(DB, 'Application',
                                               OFS.Application.Application, ())
    Zope2.bobo_application = app

    # Initialize the app object
    application = app()
    OFS.Application.initialize(application)
    if Globals.DevelopmentMode:
        # Set up auto-refresh.
        from App.RefreshFuncs import setupAutoRefresh
        setupAutoRefresh(application._p_jar)
    application._p_jar.close()

    # "Log off" as system user
    noSecurityManager()

    global startup_time
    startup_time = asctime()

    notify(DatabaseOpenedWithRoot(DB))

    Zope2.zpublisher_transactions_manager = TransactionsManager()
    Zope2.zpublisher_exception_hook = zpublisher_exception_hook
    Zope2.zpublisher_validated_hook = validated_hook
    Zope2.__bobo_before__ = noSecurityManager
Example #52
0
def startup():
    patch_persistent()

    global app

    # Import products
    OFS.Application.import_products()

    configuration = getConfiguration()

    # Open the database
    dbtab = configuration.dbtab
    try:
        # Try to use custom storage
        try:
            m = imp.find_module('custom_zodb', [configuration.testinghome])
        except Exception:
            m = imp.find_module('custom_zodb', [configuration.instancehome])
    except Exception:
        # if there is no custom_zodb, use the config file specified databases
        DB = dbtab.getDatabase('/', is_root=1)
    else:
        m = imp.load_module('Zope2.custom_zodb', m[0], m[1], m[2])
        sys.modules['Zope2.custom_zodb'] = m

        # Get the database and join it to the dbtab multidatabase
        # FIXME: this uses internal datastructures of dbtab
        databases = getattr(dbtab, 'databases', {})
        if hasattr(m, 'DB'):
            DB = m.DB
            databases.update(getattr(DB, 'databases', {}))
            DB.databases = databases
        else:
            DB = ZODB.DB(m.Storage, databases=databases)

    # Force a connection to every configured database, to ensure all of them
    # can indeed be opened. This avoids surprises during runtime when traversal
    # to some database mountpoint fails as the underlying storage cannot be
    # opened at all
    if dbtab is not None:
        for mount, name in dbtab.listMountPaths():
            _db = dbtab.getDatabase(mount)
            _conn = _db.open()
            _conn.close()
            del _conn
            del _db

    notify(DatabaseOpened(DB))

    Zope2.DB = DB
    Zope2.opened.append(DB)

    from . import ClassFactory
    DB.classFactory = ClassFactory.ClassFactory

    # "Log on" as system user
    newSecurityManager(None, AccessControl.User.system)

    # Set up the CA
    load_zcml()

    # Set up the "app" object that automagically opens
    # connections
    app = App.ZApplication.ZApplicationWrapper(DB, 'Application',
                                               OFS.Application.Application)
    Zope2.bobo_application = app

    # Initialize the app object
    application = app()
    OFS.Application.initialize(application)
    application._p_jar.close()

    # "Log off" as system user
    noSecurityManager()

    global startup_time
    startup_time = asctime()

    notify(DatabaseOpenedWithRoot(DB))
Example #53
0
 def login(self, quiet=0, run=run_all_test):
     uf = self.getPortal().acl_users
     uf._doAddUser('seb', '', ['Manager'], [])
     uf._doAddUser('ERP5TypeTestCase', '', ['Manager'], [])
     user = uf.getUserById('seb').__of__(uf)
     newSecurityManager(None, user)
Example #54
0
 def login(self, uid='god'):
     """ Login as manager """
     user = self.portal.acl_users.getUser(uid)
     newSecurityManager(None, user.__of__(self.portal.acl_users))
Example #55
0
def spoofRequest(app):
    """
    Make REQUEST variable to be available on the Zope application server.

    This allows acquisition to work properly
    """
    _policy = PermissiveSecurityPolicy()
    _oldpolicy = setSecurityPolicy(_policy)  # noqa
    newSecurityManager(None, OmnipotentUser().__of__(app.acl_users))
    return makerequest(app)


app = spoofRequest(app)  # noqa

user = app.acl_users.getUser('admin')  # noqa
newSecurityManager(None, user.__of__(app.acl_users))  # noqa
site = app[args.site_id]
setSite(site)

export_path = os.path.abspath('./archives.json')
catalog = site.portal_catalog
workflow = site.portal_workflow
ptool = site.plone_utils
site_path = '/'.join(site.getPhysicalPath())


def runExport(brains):
    items = []
    for brain in brains:
        items.append({'path': brain.getPath(), 'uid': brain.UID})
        if len(items) % 100 == 0:
Example #56
0
def validated_hook(request, user):
    newSecurityManager(request, user)
Example #57
0
    def activeSense(self, fixit=0, activate_kw=(), params=None):
        """
    This method launches the sensing process as activities.
    It is intended to launch a very long process made
    of many activities. It returns nothing since the results
    are collected in an active process.

    The result of the sensing process can be obtained by invoking
    the sense method or by requesting a report.
    """
        activate_kw = dict(activate_kw)

        if (fixit or not self.getEnabled()
            ) and not self.getPortalObject().portal_membership.checkPermission(
                Permissions.ManagePortal, self):
            raise Unauthorized(
                'fixing problems or activating a disabled alarm is not allowed'
            )

        # Use UnrestrictedMethod, so that the behaviour would not
        # change even if this method is invoked by random users.
        @UnrestrictedMethod
        def _activeSense():
            # Set the next date at which this method should be invoked
            self.setNextAlarmDate()

            # Find the active sensing method and invoke it
            # as an activity so that we can benefit from
            # distribution of alarm processing as soon as possible
            method_id = self.getActiveSenseMethodId()
            if method_id not in (None, ''):
                # A tag is provided as a parameter in order to be
                # able to notify the user after all processes are ended
                # We do some inspection to keep compatibility
                # (because fixit and tag were not set previously)
                if 'tag' not in activate_kw:
                    # If a given alarm is running more than once at a given point in
                    # time, there is a risk that the same random value will have been
                    # produced.
                    # In such event, notify() will be delayed until all conflicting
                    # invocations are done executing.
                    # Also, all notifications will as a result refer to a single
                    # ActiveProcess, so all but one notification content will be lost to
                    # someone only checking notification content.
                    # This is expected to be highly unlikely to have any meaningful
                    # effect, because:
                    # - if a single alarm can be running multiple times in parallel and
                    #   has notifications enabled, there is anyway no guarantee that each
                    #   payload will actually be properly notified (independently from
                    #   any tag collision)
                    # - if a single alarm is not usually happening in parallel and
                    #   notifications are enabled (hence, there is a reasonable
                    #   expectation that each notification will properly happen),
                    #   parallel execution means a former invocation failed, so
                    #   administrator attention should already be attracted to the issue.
                    # - and overall, alarm concurrency should be low enough that
                    #   collision should stay extremely low: it should be extremely rare
                    #   for a notification-neabled alarm to run even 10 times in parallel
                    #   (as alarms can at most be spawned every minute), and even in such
                    #   case the probability of a collision is about 2e-9 (10 / 2**32).
                    #   Assuming 10 alarms spawned every second with a one-second duration
                    #   it takes a bit under 7 years for a single collision to be more
                    #   likely to have occurred than not: 50% / (10 / 2**32) = 6.8 years
                    # On the other hand, using a completely constant tag per alarm would
                    # mean notify() would be blocked by any isolated failure event, which
                    # increases the pressure on a timely resolution of what could be a
                    # frequent occurrence (ex: an alarm pulling data from a 3rd-party
                    # server with poor availability).
                    activate_kw['tag'] = '%s_%x' % (self.getRelativeUrl(),
                                                    getrandbits(32))
                tag = activate_kw['tag']
                method = getattr(self, method_id)
                func_code = method.__code__
                try:
                    has_kw = func_code.co_flags & CO_VARKEYWORDS
                except AttributeError:
                    # XXX guess presence of *args and **kw
                    name_list = func_code.co_varnames[func_code.co_argcount:]
                    has_args = bool(name_list and name_list[0] == 'args')
                    has_kw = bool(
                        len(name_list) > has_args
                        and name_list[has_args] == 'kw')
                name_list = func_code.co_varnames[:func_code.co_argcount]
                if 'params' in name_list or has_kw:
                    # New New API
                    getattr(self.activate(**activate_kw),
                            method_id)(fixit=fixit, tag=tag, params=params)
                elif 'fixit' in name_list:
                    # New API - also if variable number of named parameters
                    getattr(self.activate(**activate_kw),
                            method_id)(fixit=fixit, tag=tag)
                else:
                    # Old API
                    getattr(self.activate(**activate_kw), method_id)()
                if self.isAlarmNotificationMode():
                    self.activate(after_tag=tag).notify(include_active=True,
                                                        params=params)

        # switch to nobody temporarily so that unrestricted _activeSense
        # is always invoked by system user.
        sm = getSecurityManager()
        newSecurityManager(None, nobody)

        try:
            _activeSense()
        finally:
            # Restore the original user.
            setSecurityManager(sm)
Example #58
0
 def afterSetUp(self):
     self.root = self.app
     newSecurityManager(None, UnrestrictedUser('god', '', ['Manager'], ''))
Example #59
0
 def loginManager(self):
     user = OmnipotentUser().__of__(self.root)
     newSecurityManager(None, user)
Example #60
0
 def login(self, *args, **kw):
     uf = self.getPortal().acl_users
     uf._doAddUser('seb', '', ['Manager'], [])
     user = uf.getUserById('seb').__of__(uf)
     newSecurityManager(None, user)