Пример #1
0
def _modifyPermissionMappings(ob, map):
    """
    Modifies multiple role to permission mappings.
    """
    # This mimics what AccessControl/Role.py does.
    # Needless to say, it's crude. :-(
    something_changed = 0
    perm_info = _ac_inherited_permissions(ob, 1)
    for name, settings in map.items():
        cur_roles = rolesForPermissionOn(name, ob)
        if isinstance(cur_roles, basestring):
            cur_roles = [cur_roles]
        else:
            cur_roles = list(cur_roles)
        changed = 0
        for (role, allow) in settings.items():
            if not allow:
                if role in cur_roles:
                    changed = 1
                    cur_roles.remove(role)
            else:
                if role not in cur_roles:
                    changed = 1
                    cur_roles.append(role)
        if changed:
            data = ()  # The list of methods using this permission.
            for perm in perm_info:
                n, d = perm[:2]
                if n == name:
                    data = d
                    break
            p = Permission(name, data, ob)
            p.setRoles(tuple(cur_roles))
            something_changed = 1
    return something_changed
Пример #2
0
def manage_permission_for(brain_or_object, permission, roles, acquire=0):
    """Change the settings for the given permission.

    Code extracted from `IRoleManager.manage_permission`

    :param brain_or_object: Catalog brain or object
    :param permission: The permission to be granted
    :param roles: The roles the permission to be granted to
    :param acquire: Flag to acquire the permission
    """
    obj = api.get_object(brain_or_object)

    if isinstance(roles, basestring):
        roles = [roles]

    for item in obj.ac_inherited_permissions(1):
        name, value = item[:2]
        if name == permission:
            permission = Permission(name, value, obj)
            if acquire:
                roles = list(roles)
            else:
                roles = tuple(roles)
            permission.setRoles(roles)
            return

    # Raise an error if the permission is invalid
    raise ValueError("The permission {} is invalid.".format(permission))
Пример #3
0
def _modifyPermissionMappings(ob, map):
    """
    Modifies multiple role to permission mappings.
    """
    # This mimics what AccessControl/Role.py does.
    # Needless to say, it's crude. :-(
    something_changed = 0
    perm_info = _ac_inherited_permissions(ob, 1)
    for name, settings in map.items():
        cur_roles = rolesForPermissionOn(name, ob)
        if isinstance(cur_roles, basestring):
            cur_roles = [cur_roles]
        else:
            cur_roles = list(cur_roles)
        changed = 0
        for (role, allow) in settings.items():
            if not allow:
                if role in cur_roles:
                    changed = 1
                    cur_roles.remove(role)
            else:
                if role not in cur_roles:
                    changed = 1
                    cur_roles.append(role)
        if changed:
            data = ()  # The list of methods using this permission.
            for perm in perm_info:
                n, d = perm[:2]
                if n == name:
                    data = d
                    break
            p = Permission(name, data, ob)
            p.setRoles(tuple(cur_roles))
            something_changed = 1
    return something_changed
Пример #4
0
    def manage_changePermissions(self, REQUEST):
        """Change all permissions settings, called by management screen.
        """
        valid_roles = self.valid_roles()
        indexes = range(len(valid_roles))
        have = REQUEST.has_key
        permissions = self.ac_inherited_permissions(1)
        fails = []
        for ip in range(len(permissions)):
            roles = []
            for ir in indexes:
                if have("p%dr%d" % (ip, ir)):
                    roles.append(valid_roles[ir])
            name, value = permissions[ip][:2]
            try:
                p = Permission(name, value, self)
                if not have('a%d' % ip):
                    roles = tuple(roles)
                p.setRoles(roles)
            except:
                fails.append(name)

        if fails:
            return MessageDialog(title="Warning!",
                                 message="Some permissions had errors: " +
                                 escape(', '.join(fails)),
                                 action='manage_access')
        return MessageDialog(title='Success!',
                             message='Your changes have been saved',
                             action='manage_access')
Пример #5
0
    def manage_changePermissions(self, REQUEST):
        """Change all permissions settings, called by management screen.
        """
        valid_roles=self.valid_roles()
        indexes=range(len(valid_roles))
        have=REQUEST.has_key
        permissions=self.ac_inherited_permissions(1)
        fails = []
        for ip in range(len(permissions)):
            roles = []
            for ir in indexes:
                if have("p%dr%d" % (ip, ir)):
                    roles.append(valid_roles[ir])
            name, value = permissions[ip][:2]
            try:
                p = Permission(name, value, self)
                if not have('a%d' % ip):
                    roles=tuple(roles)
                p.setRoles(roles)
            except:
                fails.append(name)

        if fails:
            return MessageDialog(title="Warning!",
                                 message="Some permissions had errors: "
                                   + escape(', '.join(fails)),
                                 action='manage_access')
        return MessageDialog(
            title = 'Success!',
            message = 'Your changes have been saved',
            action = 'manage_access')
Пример #6
0
    def manage_changePermissions(self, REQUEST):
        """Change all permissions settings, called by management screen."""
        valid_roles = self.valid_roles()
        have = REQUEST.__contains__
        permissions = self.ac_inherited_permissions(1)
        fails = []
        for ip in range(len(permissions)):
            permission_name = permissions[ip][0]
            permission_hash = _string_hash(permission_name)
            roles = []
            for role in valid_roles:
                role_name = role
                role_hash = _string_hash(role_name)
                if have("permission_%srole_%s" % (permission_hash, role_hash)):
                    roles.append(role)
            name, value = permissions[ip][:2]
            try:
                p = Permission(name, value, self)
                if not have('acquire_%s' % permission_hash):
                    roles = tuple(roles)
                p.setRoles(roles)
            except Exception:
                fails.append(name)

        if fails:
            raise BadRequest('Some permissions had errors: ' +
                             html.escape(', '.join(fails), True))
        if REQUEST is not None:
            return self.manage_access(REQUEST)
def update(app):
    catalog = getattr(app, 'Catalog')
    brains = catalog(meta_type='Report Document')

    for brain in brains:
        doc = brain.getObject()
        valid_roles = doc.valid_roles()

        if 'Auditor' in valid_roles:
            permissions = doc.ac_inherited_permissions(1)
            for perm in permissions:
                name, value = perm[:2]
                if name == 'View':
                    p = Permission(name, value, doc)
                    roles = list(p.getRoles())
                    if 'Auditor' not in roles:
                        roles.append('Auditor')
                        roles = tuple(roles)
                        try:
                            p.setRoles(roles)
                            print "Added Auditor to View permission for %s" % doc.absolute_url()
                        except:
                            print "Failed"

    transaction.commit()
Пример #8
0
def tryMethodCallWithTemporaryPermission(context, permission, method,
    method_argv, method_kw, exception):
  # we want to catch the explicit security check done in manage_renameObject
  # and bypass it. for this, we temporarily give the Copy or Move right to the
  # user. We assume that if the user has enough rights to pass the
  # "declareProtected" check around "setId", he should be really able to
  # rename the object.
  try:
    return method(*method_argv, **method_kw)
  except exception:
    user = getSecurityManager().getUser()
    user_role_list = user.getRolesInContext(context)
    if len(user_role_list) > 0:
      perm_list = context.ac_inherited_permissions()
      for p in perm_list:
        if p[0] == permission:
          name, value = p[:2]
          break
      else:
        name, value = (permission, ())
      p = Permission(name,value,context)
      old_role_list = p.getRoles(default=[])
      p.setRoles(user_role_list)
      result = method(*method_argv, **method_kw)
      p.setRoles(old_role_list)
      return result
Пример #9
0
 def testChangeUseOpenFlowPermission(self):
     from AccessControl.Permission import Permission
     perms = self.of.ac_inherited_permissions(1)
     name, value = [p for p in perms if p[0]=='Use OpenFlow'][0][:2]
     p=Permission(name,value,self.of)
     roles = ['Authenticated']
     p.setRoles(roles)
Пример #10
0
    def manage_changePermissions(self, REQUEST):
        """Change all permissions settings, called by management screen."""
        valid_roles = self.valid_roles()
        have = REQUEST.__contains__
        permissions = self.ac_inherited_permissions(1)
        fails = []
        for ip in range(len(permissions)):
            permission_name = permissions[ip][0]
            permission_hash = _string_hash(permission_name)
            roles = []
            for role in valid_roles:
                role_name = role
                role_hash = _string_hash(role_name)
                if have("permission_%srole_%s" % (permission_hash, role_hash)):
                    roles.append(role)
            name, value = permissions[ip][:2]
            try:
                p = Permission(name, value, self)
                if not have('acquire_%s' % permission_hash):
                    roles = tuple(roles)
                p.setRoles(roles)
            except Exception:
                fails.append(name)

        if fails:
            raise BadRequest('Some permissions had errors: '
                             + escape(', '.join(fails), True))
        if REQUEST is not None:
            return self.manage_access(REQUEST)
Пример #11
0
def tryMethodCallWithTemporaryPermission(context, permission, method,
    method_argv, method_kw, exception):
  # we want to catch the explicit security check done in manage_renameObject
  # and bypass it. for this, we temporarily give the Copy or Move right to the
  # user. We assume that if the user has enough rights to pass the
  # "declareProtected" check around "setId", he should be really able to
  # rename the object.
  try:
    return method(*method_argv, **method_kw)
  except exception:
    user = getSecurityManager().getUser()
    user_role_list = user.getRolesInContext(context)
    if len(user_role_list) > 0:
      perm_list = context.ac_inherited_permissions()
      for p in perm_list:
        if p[0] == permission:
          name, value = p[:2]
          break
      else:
        name, value = (permission, ())
      p = Permission(name,value,context)
      old_role_list = p.getRoles(default=[])
      p.setRoles(user_role_list)
      result = method(*method_argv, **method_kw)
      p.setRoles(old_role_list)
      return result
Пример #12
0
    def _update(self, portal):
        layout_permission = Permission(view, (), portal.portal_layout)
        layout_permission.setRoles(portal.validRoles())

        dyn_permission = Permission(view, (), portal.portal_dynamicproperties)
        dyn_permission.setRoles(portal.validRoles())
        self.log.info('Done')
        return True
Пример #13
0
    def setPermissionMapping(self, mapping):
        """
        Change the permission mapping for the object.
        This leaves the other permissions (not in mapping.keys()) unchanged
        """

        for permission in mapping:
            permission_object = Permission(permission, (), self.getObject())
            permission_object.setRoles(mapping[permission])
 def _update(self, portal):
     view_perm = Permission(view, (), portal)
     roles_with_view = view_perm.getRoles()
     if tuple is type(roles_with_view):
         self.log.debug('No need to update')
     else:
         view_perm.setRoles(tuple(roles_with_view))
         self.log.debug('Removed view permission inheritance for the site')
     return True
Пример #15
0
 def _update(self, portal):
     layout_tool = portal.getLayoutTool()
     view_perm = Permission(view, (), layout_tool)
     if 'Anonymous' not in view_perm.getRoles():
         view_perm.setRoles(['Anonymous',])
         self.log.info("View Permission set for Anonymous on portal_layout.")
     else:
         self.log.info("Already has it, nothing to do.")
     return True
 def _update(self, portal):
     skip_captcha_perm = Permission('Naaya - Skip Captcha', (), portal)
     roles_with_skip_captcha = skip_captcha_perm.getRoles()
     if 'Authenticated' not in roles_with_skip_captcha:
         roles_with_skip_captcha.append('Authenticated')
         skip_captcha_perm.setRoles(roles_with_skip_captcha)
         self.log.debug('Skip Captcha permission assigned to Authenticated')
     else:
         self.log.debug('Authenticated already has the permission')
     return True
Пример #17
0
def manage_addLayoutTool(self, REQUEST=None):
    """ """
    ob = LayoutTool(ID_LAYOUTTOOL, TITLE_LAYOUTTOOL)
    self._setObject(ID_LAYOUTTOOL, ob)
    ob_aq = self._getOb(ID_LAYOUTTOOL)
    ob_aq.loadDefaultData()
    view_perm = Permission(view, (), ob_aq)
    view_perm.setRoles(['Anonymous',])
    if REQUEST:
        return self.manage_main(self, REQUEST, update_menu=1)
 def _update(self, portal):
     skip_captcha_perm = Permission('Naaya - Skip Captcha', (), portal)
     roles_with_skip_captcha = skip_captcha_perm.getRoles()
     if 'Authenticated' not in roles_with_skip_captcha:
         roles_with_skip_captcha.append('Authenticated')
         skip_captcha_perm.setRoles(roles_with_skip_captcha)
         self.log.debug('Skip Captcha permission assigned to Authenticated')
     else:
         self.log.debug('Authenticated already has the permission')
     return True
Пример #19
0
    def setPermissionMapping(self, mapping):
        """
        Change the permission mapping for the parent.
        This leaves the other permissions (not in mapping.keys()) unchanged
        """
        for zope_perm in mapping:
            permission = Permission(zope_perm, (), self.aq_parent)
            permission.setRoles(mapping[zope_perm])

        transaction.commit()
 def _update(self, portal):
     review_perm = Permission('Naaya - Review TalkBack Consultation',
                              (), portal)
     for role in ['Administrator', 'Owner', 'Reviewer']:
         roles = review_perm.getRoles()
         if role not in roles:
             roles.append(role)
             review_perm.setRoles(roles)
             self.log.info("Review Permission set for %s on %s" %
                           (role, portal.absolute_url()))
     return True
Пример #21
0
 def set_acl_for_roles(ob, roles):
     permission_object = Permission(view, (), ob)
     current_roles = permission_object.getRoles()
     is_tuple = isinstance(current_roles, tuple)
     current_roles = list(current_roles)
     new_roles = set(roles + current_roles)
     if is_tuple:
         new_roles = tuple(new_roles)
     else:
         new_roles = list(new_roles)
     permission_object.setRoles(new_roles)
Пример #22
0
def manage_addLayoutTool(self, REQUEST=None):
    """ """
    ob = LayoutTool(ID_LAYOUTTOOL, TITLE_LAYOUTTOOL)
    self._setObject(ID_LAYOUTTOOL, ob)
    ob_aq = self._getOb(ID_LAYOUTTOOL)
    ob_aq.loadDefaultData()
    view_perm = Permission(view, (), ob_aq)
    view_perm.setRoles([
        'Anonymous',
    ])
    if REQUEST:
        return self.manage_main(self, REQUEST, update_menu=1)
Пример #23
0
 def _update(self, portal):
     meetings = portal.getCatalogedObjects(meta_type='Naaya Meeting')
     for meeting in meetings:
         view_perm = Permission('View', (), meeting)
         for role in [OBSERVER_ROLE, WAITING_ROLE, PARTICIPANT_ROLE]:
             roles = view_perm.getRoles()
             if role not in roles:
                 roles.append(role)
                 view_perm.setRoles(roles)
                 self.log.info("View Permission set for %s on %s" %
                               (role, meeting.absolute_url()))
     return True
Пример #24
0
 def _update(self, portal):
     layout_tool = portal.getLayoutTool()
     view_perm = Permission(view, (), layout_tool)
     if 'Anonymous' not in view_perm.getRoles():
         view_perm.setRoles([
             'Anonymous',
         ])
         self.log.info(
             "View Permission set for Anonymous on portal_layout.")
     else:
         self.log.info("Already has it, nothing to do.")
     return True
Пример #25
0
 def _update(self, portal):
     meetings = portal.getCatalogedObjects(meta_type='Naaya Meeting')
     for meeting in meetings:
         view_perm = Permission('View', (), meeting)
         for role in [OBSERVER_ROLE, WAITING_ROLE, PARTICIPANT_ROLE]:
             roles = view_perm.getRoles()
             if role not in roles:
                 roles.append(role)
                 view_perm.setRoles(roles)
                 self.log.info("View Permission set for %s on %s" %
                               (role, meeting.absolute_url()))
     return True
Пример #26
0
 def manage_acquiredPermissions(self, permissions=[]):
     """Change the permissions that acquire.
     """
     for p in self.ac_inherited_permissions(1):
         name, value = p[:2]
         p = Permission(name, value, self)
         roles = p.getRoles()
         if roles is None:
             continue
         if name in permissions:
             p.setRoles(list(roles))
         else:
             p.setRoles(tuple(roles))
Пример #27
0
    def tearDown(self):
        self.browser_do_logout()

        self.auth_tool.manage_revokeUserRole(user=self.user_obj.name,
                                             location='/portal/info')

        # reset portal roles with view
        view_perm = Permission(view, (), self.portal)
        view_perm.setRoles(self.site_roles_with_view)

        transaction.commit()

        super(UserWithRolesOnlyOnFolderTestSetup, self).tearDown()
Пример #28
0
 def manage_acquiredPermissions(self, permissions=[]):
     """Change the permissions that acquire.
     """
     for p in self.ac_inherited_permissions(1):
         name, value = p[:2]
         p = Permission(name, value, self)
         roles = p.getRoles()
         if roles is None:
             continue
         if name in permissions:
             p.setRoles(list(roles))
         else:
             p.setRoles(tuple(roles))
    def tearDown(self):
        self.browser_do_logout()

        self.auth_tool.manage_revokeUserRole(user=self.user_obj.name,
                                             location='/portal/info')

        # reset portal roles with view
        view_perm = Permission(view, (), self.portal)
        view_perm.setRoles(self.site_roles_with_view)

        transaction.commit()

        super(UserWithRolesOnlyOnFolderTestSetup, self).tearDown()
    def _update(self, portal):
        permission = Permission('Naaya - Add comments for content', (), portal)
        roles = permission.getRoles()
        if 'Authenticated' in roles:
            self.log.debug("Portal doesn't need update")
            self.log.debug("Authenticated users can already add comments")
            return True

        if isinstance(roles, tuple):
            roles = tuple(list(roles) + ['Authenticated'])
        else:
            roles = roles + ['Authenticated']
        permission.setRoles(roles)
        return True
Пример #31
0
    def _update(self, portal):
        portal_catalog = portal.getCatalogTool()
        set_roles = ['Administrator', 'Manager']
        for brain in portal_catalog(meta_type='Naaya Forum'):
            forum = brain.getObject()
            for permission_name in (PERMISSION_MODIFY_FORUMTOPIC,
                                    PERMISSION_SKIP_CAPTCHA):
                perm = Permission(permission_name, (), forum)
                roles = perm.getRoles()
                if 'Manager' not in roles or 'Administrator' not in roles:
                    perm.setRoles(list(set(roles + set_roles)))
            self.log.debug('Default permissions added for %s', forum.absolute_url())

        return True
Пример #32
0
 def migrate_permission_settings(self):
     """Migrate permission settings (permission <-> role)
     The acquire flag is coded into the type of the sequence. If roles is a list
     than the roles are also acquire. If roles is a tuple the roles aren't
     acquired.
     """
     oldmap = getPermissionMapping(self.old.ac_inherited_permissions(1))
     newmap = getPermissionMapping(self.new.ac_inherited_permissions(1))
     for key, values in oldmap.items():
         old_p = Permission(key, values, self.old)
         old_roles = old_p.getRoles()
         new_values = newmap.get(key, ())
         new_p = Permission(key, new_values, self.new)
         new_p.setRoles(old_roles)
Пример #33
0
 def migrate_permission_settings(self):
     """Migrate permission settings (permission <-> role)
     The acquire flag is coded into the type of the sequence. If roles is a list
     than the roles are also acquire. If roles is a tuple the roles aren't
     acquired.
     """
     oldmap = getPermissionMapping(self.old.ac_inherited_permissions(1))
     newmap = getPermissionMapping(self.new.ac_inherited_permissions(1))
     for key, values in oldmap.items():
         old_p = Permission(key, values, self.old)
         old_roles = old_p.getRoles()
         new_values = newmap.get(key, ())
         new_p = Permission(key, new_values, self.new)
         new_p.setRoles(old_roles)
def allowMembersToAddCenter(obj):
    perms = [p for p in obj.ac_inherited_permissions(1) if p[0] == AddSoftwareCenter]
    p = perms[0]
    name, value = perms[0][:2]
    p = Permission(name, value, obj)
    roles = p.getRoles()
    if 'Member' not in roles:
        if type(roles) == type(()):
            roles = list(roles)
            roles.append('Member')
            roles = tuple(roles)
        else:
            roles.append('Member')
    p.setRoles(roles)
Пример #35
0
def allowMembersToAddCenter(obj):
    perms = [p for p in obj.ac_inherited_permissions(1) if p[0] == AddSoftwareCenter]
    p = perms[0]
    name, value = perms[0][:2]
    p = Permission(name, value, obj)
    roles = p.getRoles()
    if 'Member' not in roles:
        if type(roles) == type(()):
            roles = list(roles)
            roles.append('Member')
            roles = tuple(roles)
        else:
            roles.append('Member')
    p.setRoles(roles)
Пример #36
0
    def _update(self, portal):
        portal_catalog = portal.getCatalogTool()
        set_roles = ['Administrator', 'Manager']
        for brain in portal_catalog(meta_type='Naaya Forum'):
            forum = brain.getObject()
            for permission_name in (PERMISSION_MODIFY_FORUMTOPIC,
                                    PERMISSION_SKIP_CAPTCHA):
                perm = Permission(permission_name, (), forum)
                roles = perm.getRoles()
                if 'Manager' not in roles or 'Administrator' not in roles:
                    perm.setRoles(list(set(roles + set_roles)))
            self.log.debug('Default permissions added for %s',
                           forum.absolute_url())

        return True
Пример #37
0
    def setUp(self):
        super(UserWithRolesOnlyOnFolderTestSetup, self).setUp()

        # get&save roles with view
        view_perm = Permission(view, (), self.portal)
        self.site_roles_with_view = view_perm.getRoles()
        view_perm.setRoles(('Manager'))

        roles = ['Administrator', 'Manager', 'Contributor']
        self.auth_tool.manage_addUsersRoles(name=self.user_obj.name,
                                            roles=roles,
                                            location='/portal/info')

        transaction.commit()

        self.browser_do_login(self.user_name, self.user_password)
Пример #38
0
    def _update(self, portal):
        meta_type = 'Naaya Meeting'
        if not portal.is_pluggable_item_installed(meta_type):
            self.log.debug('Meeting not installed')
            return True

        self.log.debug('Adding Observer role')
        add_observer_role(portal)

        self.log.debug('Patching meeting objects')
        meetings = portal.getCatalogedObjects(meta_type)
        for meeting in meetings:
            self.log.debug('Patching meeting object at %s' % meeting.absolute_url(1))
            permission = Permission(PERMISSION_PARTICIPATE_IN_MEETING, (), meeting)
            permission.setRoles([OBSERVER_ROLE, WAITING_ROLE, PARTICIPANT_ROLE, ADMINISTRATOR_ROLE])
        return True
    def setUp(self):
        super(UserWithRolesOnlyOnFolderTestSetup, self).setUp()

        # get&save roles with view
        view_perm = Permission(view, (), self.portal)
        self.site_roles_with_view = view_perm.getRoles()
        view_perm.setRoles(('Manager'))

        roles = ['Administrator', 'Manager', 'Contributor']
        self.auth_tool.manage_addUsersRoles(name=self.user_obj.name,
                                            roles=roles,
                                            location='/portal/info')

        transaction.commit()

        self.browser_do_login(self.user_name, self.user_password)
Пример #40
0
def modifyRolesForPermission(ob, pname, roles):
    '''
    Modifies multiple role to permission mappings.  roles is a list to
    acquire, a tuple to not acquire.
    '''
    # This mimics what AccessControl/Role.py does.
    data = ()
    for perm in ac_inherited_permissions(ob, 1):
        name, value = perm[:2]
        if name == pname:
            data = value
            break
    p = Permission(pname, data, ob)
    if p.getRoles() != roles:
        p.setRoles(roles)
        return 1
    return 0
Пример #41
0
def modifyRolesForPermission(ob, pname, roles):
    '''
    Modifies multiple role to permission mappings.  roles is a list to
    acquire, a tuple to not acquire.
    '''
    # This mimics what AccessControl/Role.py does.
    data = ()
    for perm in ac_inherited_permissions(ob, 1):
        name, value = perm[:2]
        if name == pname:
            data = value
            break
    p = Permission(pname, data, ob)
    if p.getRoles() != roles:
        p.setRoles(roles)
        return 1
    return 0
Пример #42
0
    def manage_permission(self, permission_to_manage, roles=[], acquire=0):
        """Change the settings for the given permission.

        If optional arg acquire is true, then the roles for the permission
        are acquired, in addition to the ones specified, otherwise the
        permissions are restricted to only the designated roles.
        """
        for p in self.ac_inherited_permissions(1):
            name, value = p[:2]
            if name == permission_to_manage:
                p = Permission(name, value, self)
                if acquire:
                    roles = list(roles)
                else:
                    roles = tuple(roles)
                p.setRoles(roles)
                return

        raise ValueError("The permission <em>%s</em> is invalid." %
                         escape(permission_to_manage))
Пример #43
0
    def manage_permission(self, permission_to_manage, roles=[], acquire=0):
        """Change the settings for the given permission.

        If optional arg acquire is true, then the roles for the permission
        are acquired, in addition to the ones specified, otherwise the
        permissions are restricted to only the designated roles.
        """
        for p in self.ac_inherited_permissions(1):
            name, value = p[:2]
            if name == permission_to_manage:
                p = Permission(name, value, self)
                if acquire:
                    roles = list(roles)
                else:
                    roles = tuple(roles)
                p.setRoles(roles)
                return

        raise ValueError(
            "The permission <em>%s</em> is invalid." %
            escape(permission_to_manage))
Пример #44
0
    def _update(self, portal):
        meta_type = 'Naaya Meeting'
        if not portal.is_pluggable_item_installed(meta_type):
            self.log.debug('Meeting not installed')
            return True

        self.log.debug('Adding Observer role')
        add_observer_role(portal)

        self.log.debug('Patching meeting objects')
        meetings = portal.getCatalogedObjects(meta_type)
        for meeting in meetings:
            self.log.debug('Patching meeting object at %s' %
                           meeting.absolute_url(1))
            permission = Permission(PERMISSION_PARTICIPATE_IN_MEETING, (),
                                    meeting)
            permission.setRoles([
                OBSERVER_ROLE, WAITING_ROLE, PARTICIPANT_ROLE,
                ADMINISTRATOR_ROLE
            ])
        return True
def modifyRolesForPermission(obj, pname, roles):
    
    data = ()
    
    for permission in ac_inherited_permissions(obj, True):
        name, value = permission[:2]
        if name == pname:
            data = value
            break
    
    p = Permission(pname, data, obj)
    
    # Note: tuple = not acquired; list = acquired
    acquire = isinstance(roles, list)
    
    to_remove = set(roles)
    valid_roles = set(obj.validRoles()) - set(['Authenticated', 'Anonymous'])
    existing_roles = set([r for r in rolesForPermissionOn(pname, obj) if r and not r.endswith('_Permission')])
    
    # If we are taking away 'Anonymous', bear in mind that this implies "any role". 
    if 'Anonymous' in existing_roles and 'Anonymous' in to_remove:
        existing_roles.update(valid_roles)
        existing_roles.remove('Anonymous')
    
    # Similarly, 'Authenticated' implies "any role except Anonymous"
    if 'Authenticated' in existing_roles and 'Authenticated' in to_remove:
        existing_roles.update(valid_roles)
        existing_roles.remove('Authenticated')
    
    if acquire:
        new_roles = list(existing_roles - to_remove)
    else:
        new_roles = tuple(existing_roles - to_remove)
    
    if p.getRoles() != new_roles:
        p.setRoles(new_roles)
        return True
    
    return False
Пример #46
0
    def setUp(self):
        super(NyAccess2LevelTestCase, self).setUp()

        self.perm1, self.perm2 = 'View', 'View History'
        self.role1, self.role2 = 'Contributor', 'Reviewer'

        addNyFolder(self.portal.info,
                    'testfolderparent',
                    contributor='admin',
                    submission=1)
        self.testfolderparent = self.portal.info.testfolderparent

        addNyFolder(self.testfolderparent,
                    'testfolder',
                    contributor='admin',
                    submission=1)
        self.testfolder = self.testfolderparent.testfolder

        # NOTE: this is *not* the way to use NyAccess. It should never
        # be stored in the database. It should be set as an attribute
        # to a *class*, like NyForum.
        self.testfolderparent._setOb(
            'ny_access',
            NyAccess('ny_access', {
                self.perm1: self.perm1,
                self.perm2: self.perm2
            }))

        self.testfolder._setOb(
            'ny_access',
            NyAccess('ny_access', {
                self.perm1: self.perm1,
                self.perm2: self.perm2
            }))

        # default permission map
        # parent folder does not inherit permissions
        permission = Permission(self.perm1, (), self.testfolderparent)
        permission.setRoles((self.role1, 'Manager'))
        permission = Permission(self.perm2, (), self.testfolderparent)
        permission.setRoles((self.role2, 'Manager'))
        # child folder permissions
        permission = Permission(self.perm1, (), self.testfolder)
        permission.setRoles([self.role2])
        permission = Permission(self.perm2, (), self.testfolder)
        permission.setRoles((self.role1, 'Manager'))

        transaction.commit()
Пример #47
0
def removePermissionsForRole(context, role, wanted_permissions):
    """ Remove permissions for a role in the context.

    Parameters:
        @param context Portal object (portal itself, Archetypes item, any inherited from RoleManager)
        @param role role name, as a string
        @param wanted_permissions tuple of permissions (string names) to add for the role    

    All wanted_permissions lose their acquiring ability
    """

    assert type(wanted_permissions) == types.TupleType

    # print "Doing role:" + role + " perms:" + str(wanted_permissions)
    for p in context.ac_inherited_permissions(all=True):
        name, value = p[:2]
        p = Permission(name, value, context)
        roles = list(p.getRoles())

        # print "Permission:" + name + " roles " + str(roles)
        if name in wanted_permissions:
            if role in roles:
                roles.remove(role)
            p.setRoles(tuple(roles))
Пример #48
0
def removePermissionsForRole(context, role, wanted_permissions):
    """ Remove permissions for a role in the context.

    Parameters:
        @param context Portal object (portal itself, Archetypes item, any inherited from RoleManager)
        @param role role name, as a string
        @param wanted_permissions tuple of permissions (string names) to add for the role    

    All wanted_permissions lose their acquiring ability
    """        

    assert type(wanted_permissions) == tuple

    #print "Doing role:" + role + " perms:" + str(wanted_permissions)
    for p in context.ac_inherited_permissions(all=True):
        name, value = p[:2]
        p=Permission(name, value, context)
        roles=list(p.getRoles())

        #print "Permission:" + name + " roles " + str(roles)
        if name in wanted_permissions:
            if role in roles:
                roles.remove(role)
            p.setRoles(tuple(roles))
Пример #49
0
    def setUp(self):
        super(NyAccess2LevelTestCase, self).setUp()

        self.perm1, self.perm2 = 'View', 'View History'
        self.role1, self.role2 = 'Contributor', 'Reviewer'

        addNyFolder(self.portal.info,
                    'testfolderparent',
                    contributor='admin',
                    submission=1)
        self.testfolderparent = self.portal.info.testfolderparent

        addNyFolder(self.testfolderparent,
                    'testfolder',
                    contributor='admin',
                    submission=1)
        self.testfolder = self.testfolderparent.testfolder

        # NOTE: this is *not* the way to use NyAccess. It should never
        # be stored in the database. It should be set as an attribute
        # to a *class*, like NyForum.
        self.testfolderparent._setOb('ny_access',
                NyAccess('ny_access',
                         {self.perm1: self.perm1, self.perm2: self.perm2}))

        self.testfolder._setOb('ny_access',
                NyAccess('ny_access',
                         {self.perm1: self.perm1, self.perm2: self.perm2}))

        # default permission map
        # parent folder does not inherit permissions
        permission = Permission(self.perm1, (), self.testfolderparent)
        permission.setRoles((self.role1, 'Manager'))
        permission = Permission(self.perm2, (), self.testfolderparent)
        permission.setRoles((self.role2, 'Manager'))
        # child folder permissions
        permission = Permission(self.perm1, (), self.testfolder)
        permission.setRoles([self.role2])
        permission = Permission(self.perm2, (), self.testfolder)
        permission.setRoles((self.role1, 'Manager'))

        transaction.commit()
Пример #50
0
 def inherit_view_permission(self):
     permission = Permission(view, (), self)
     roles = permission.getRoles()
     roles = list(roles)
     permission.setRoles(roles)
Пример #51
0
 def dont_inherit_view_permission(self):
     permission = Permission(view, (), self)
     roles = permission.getRoles()
     roles = tuple(set(roles) | set(['Manager', 'Administrator', 'Owner']))
     permission.setRoles(roles)
Пример #52
0
    def test_with_captcha(self):
        """
        Test for captcha: does it show up when it's supposed to? Is it really
        verified?
        """
        self.portal.acl_users._doAddUser('other_user', 'other_user', [], '',
                                    'Other', 'User', '*****@*****.**')
        zperm = self.portal.get_pluggable_item(self.meta_type)['permission']
        p = Permission(zperm, (), self.portal)
        p.setRoles(p.getRoles() + ['Authenticated'])
        transaction.commit()

        self.login_user('other_user', 'other_user')

        self.selenium.open('/portal/info/', True)
        self.selenium.select('typetoadd', 'label=%s' % self.meta_label)
        self.selenium.wait_for_page_to_load(self._selenium_page_timeout)

        assert self.selenium.is_element_present(
                '//input[@name="test-captcha-response"]')

        self._fill_add_form()

        # submit with no captcha response
        self.selenium.click("//input[@value='Submit']")
        self.selenium.wait_for_page_to_load(self._selenium_page_timeout)
        assert self.selenium.is_text_present("Verification words do not match "
                                             "the ones in the picture.")

        # submit with incorrect captcha response
        self.selenium.type('test-captcha-response', "blah blah")
        self.selenium.click("//input[@value='Submit']")
        self.selenium.wait_for_page_to_load(self._selenium_page_timeout)
        assert self.selenium.is_text_present("Verification words do not match "
                                             "the ones in the picture.")

        challenge = self.selenium.get_text(
                '//span[@id="test-captcha-challenge"]')
        response = mock_captcha.solve(challenge)
        self.selenium.type('test-captcha-response', response)

        # submit with proper response
        self.selenium.click("//input[@value='Submit']")
        self.selenium.wait_for_page_to_load(self._selenium_page_timeout)
        assert self.selenium.is_text_present('The administrator will analyze')

        transaction.abort()
        self._assert_object_added_properly(self.portal['info'],
                                           submitter='other_user')

        # "skip captcha" permission
        p = Permission('Naaya - Skip Captcha', (), self.portal)
        p.setRoles(p.getRoles() + ['Authenticated'])
        transaction.commit()

        self.selenium.open('/portal/info/', True)
        self.selenium.select('typetoadd', 'label=%s' % self.meta_label)
        self.selenium.wait_for_page_to_load(self._selenium_page_timeout)

        assert not self.selenium.is_element_present(
                '//input[@name="test-captcha-response"]')

        self.logout_user()
Пример #53
0
def permission_del_role(context, permission, role):
    """ Removes permission from role """
    p = Permission(permission, (), context)
    crt_roles = p.getRoles()
    ty = type(crt_roles)
    p.setRoles(ty(set(crt_roles) - set([role])))
Пример #54
0
 def dont_inherit_view_permission(self):
     permission = Permission(view, (), self)
     roles = permission.getRoles()
     roles = tuple(set(roles) | set(['Manager', 'Administrator', 'Owner']))
     permission.setRoles(roles)
Пример #55
0
def permission_add_role(context, permission, role):
    """ Adds a role to a permission"""
    p = Permission(permission, (), context)
    crt_roles = p.getRoles()
    ty = type(crt_roles)
    p.setRoles(ty(set(crt_roles) | set([role])))
Пример #56
0
 def inherit_view_permission(self):
     permission = Permission(view, (), self)
     roles = permission.getRoles()
     roles = list(roles)
     permission.setRoles(roles)