def test_doActionFor_mixture(self): wftool = self.site.portal_workflow wf = self._getDummyWorkflow() # This time, disallow Authenticated and Manager wf.states['confidential'].permission_roles = {'View': ('Authenticated', 'Manager'),} dummy = DummyContent() # Now, if the item is normally granted to these roles dummy.manage_permission('View', ['Authenticated', 'Manager', 'Owner',], acquire=1) dummy = self.site._setObject('dummy', dummy) # These are the roles we know about self.assertEqual(['Anonymous', 'Authenticated', 'Manager', 'Owner'], sorted(dummy.validRoles())) self.assertEqual(wf._getStatusOf(dummy), {'state': 'nonconfidential', 'comments': ''}) # Then in the non-confidential state (no permissions ticked) we still have that role self.assertEquals(['Authenticated', 'Manager', 'Owner'], sorted(rolesForPermissionOn('View', dummy))) wf.doActionFor(dummy, 'make_confidential', comment='foo' ) self.assertEqual(wf._getStatusOf(dummy), {'state': 'confidential', 'comments': 'foo'}) # But after moving to confidential, which disallows Anonymous and Authenticated, # we are left with Owner and Manager self.assertEquals(['Owner'], sorted(rolesForPermissionOn('View', dummy)))
def test_with_permissions_subtracts(self): wftool = self.site.portal_workflow wf1, wf2 = self._getDummyWorkflows() dummy = self.site._setObject('dummy', DummyContent()) # These are the roles we know about self.assertEquals(['Anonymous', 'Authenticated', 'Manager', 'Owner'], sorted(dummy.validRoles())) self.assertEqual(wf1._getStatusOf(dummy), {'state': 'private', 'comments': ''}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': ''}) # When private and confidential, manager has the permission self.assertEquals(['Manager'], sorted(rolesForPermissionOn('View', dummy))) wftool.doActionFor(dummy, 'publish', comment='foo') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'published', 'comments': 'foo'}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': ''}) # The item is now accessible to manager self.assertEquals(['Manager'], sorted(rolesForPermissionOn('View', dummy))) wftool.doActionFor(dummy, 'make_non_confidential', comment='foo') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'published', 'comments': 'foo'}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'nonconfidential', 'comments': 'foo'}) # The item is now accessible to anonymous and owner self.assertEquals(['Anonymous', 'Owner'], sorted(rolesForPermissionOn('View', dummy)))
def test13TestCMFLRBehaviour(self, ): """Special test to check that CMF's allowedRolesAndUsers is okay """ # Allowed patterns normal_allowed = [ 'r1', 'r2', 'r3', 'user:group_g1', 'user:u6', 'user:u3' ] normal_allowed.sort() blocked_allowed = [ "r1", "r2", "r3", "user:u3", "user:u6", ] blocked_allowed.sort() # Normal behaviour ob = self.subsublr2 allowed = {} for r in rolesForPermissionOn('View', ob): allowed[r] = 1 localroles = _mergedLocalRoles(ob) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] allowed = list(allowed.keys()) allowed.sort() self.failUnlessEqual(allowed, normal_allowed) # LR-blocking behaviour self.gruf._acquireLocalRoles(self.sublr2, 0) ob = self.subsublr2 allowed = {} for r in rolesForPermissionOn('View', ob): allowed[r] = 1 localroles = _mergedLocalRoles(ob) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] allowed = list(allowed.keys()) allowed.sort() self.failUnlessEqual(allowed, blocked_allowed)
def xform_data(self, datacontainer, form): if form.has_key(self.id): roles = form[self.id] if type(roles) == types.StringType: roles = [roles] else: id = form.get('id', None) # if we have an ID, we should be dealing with the real object # rather than it's container if id: obj = getattr(datacontainer, id) else: obj = datacontainer roles = rolesForPermissionOn(self.permission_to_manage, obj) # we remove the Manager role, because we should never be adding/removing # it try: roles.remove('Manager') roles.remove('Owner') except: pass f = """<%s>%s</%s>""" % (self.id, ' '.join(roles), self.id) return f
def _checkPermission(permission, obj, StringType=type('')): roles = rolesForPermissionOn(permission, obj) if type(roles) in (StringType, UnicodeType): roles = [roles] context = getSecurityManager()._context # check executable owner and proxy roles # this code is ported from ZopeSecurityPolicy.validate stack = context.stack if stack: eo = stack[-1] owner = eo.getOwner() if owner is not None: if not owner.allowed(obj, roles): return 0 proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: if obj is not aq_base(obj): if not owner._check_context(obj): return 0 for r in proxy_roles: if r in roles: return 1 return 0 return context.user.allowed(obj, roles)
def _checkPermission(permission, obj): """ Check if the current user has the permission on the given object. """ # this code is ported from ZopeSecurityPolicy.checkPermission roles = rolesForPermissionOn(permission, obj) if isinstance(roles, basestring): roles = [roles] context = getSecurityManager()._context # check executable owner and proxy roles # this code is ported from ZopeSecurityPolicy.validate stack = context.stack if stack: eo = stack[-1] owner = eo.getOwner() if owner is not None: if not owner.allowed(obj, roles): return 0 proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: if obj is not aq_base(obj): if not owner._check_context(obj): return 0 for r in proxy_roles: if r in roles: return 1 return 0 return context.user.allowed(obj, roles)
def create_content(self): # We can only initiate if the image is publicly visible if 'Anonymous' not in rolesForPermissionOn('View', self.context): # Reset self.ready = None self.id = None return image_url = self.image_url is_local = '://localhost:' in image_url or '://127.' in image_url if DEBUG and is_local: image_url = SAMPLE_DEBUG_IMAGE elif is_local: return if self.ready: # Updating an already processed image, we need to force a # new URL (and avoid possible front-end caches) image_url = '%s?cachebust=%s' % (image_url, time.time()) request = urllib2.Request('%s?url=%s' % (ZOOMIT_UPLOAD_URL, quote_plus(image_url)), headers={"Accept": "application/json"}) try: response = opener.open(request) except urllib2.HTTPError, response: pass
def checkPermission(self, permission, object, context): if permission == 'forbidden permission': return 0 roles = rolesForPermissionOn(permission, object) if isinstance(roles, basestring): roles=[roles] return context.user.allowed(object, roles)
def _checkPermission(permission, obj, StringType = type('')): roles = rolesForPermissionOn(permission, obj) if type(roles) in (StringType, UnicodeType): roles=[roles] context = getSecurityManager()._context # check executable owner and proxy roles # this code is ported from ZopeSecurityPolicy.validate stack = context.stack if stack: eo = stack[-1] owner = eo.getOwner() if owner is not None: if not owner.allowed(obj, roles): return 0 proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: if obj is not aq_base(obj): if not owner._check_context(obj): return 0 for r in proxy_roles: if r in roles: return 1 return 0 return context.user.allowed(obj, roles)
def subscribeTo(self, obj, email=None): """Subscribe ``email`` (or the current user if ``email`` is None) to ``obj``. """ if not self.isExtraSubscriptionsEnabled(): raise DisabledFeature if email is not None: if not self.isExtraSubscriptionsForAuthenticatedOnly(): raise DisabledFeature if not EMAIL_REGEXP.match(email): raise InvalidEmailAddress allowed_roles = rolesForPermissionOn(SUBSCRIBE_PERMISSION, obj) if 'Anonymous' not in allowed_roles: raise Unauthorized ## FIXME: We would like to send an email to ask the user ## to confirm its subscription. Since this has not yet ## been implemented, we raise an error. (Damien) raise NotImplementedError elif not self.currentUserHasSubscribePermissionOn(obj): raise Unauthorized else: user = getSecurityManager().getUser().getId() self._updateSubscriptionMapping(obj) path = self._getPath(obj) subscribers = self._subscriptions.get(path, {}) subscribers[user] = 1 self._subscriptions[path] = subscribers
def _anonymousShouldBeNotified(self, obj): """Return ``True`` iff anonymous users should be notified. It returns ``True`` iff anonymous users have the ``View`` permission on ``obj``. """ return 'Anonymous' in rolesForPermissionOn('View', obj)
def _checkPermission(permission, obj, StringType = type('')): roles = rolesForPermissionOn(permission, obj) if type(roles) is StringType: roles=[roles] if _getAuthenticatedUser( obj ).allowed( obj, roles ): return 1 return 0
def allowedRolesAndUsers(obj): """Return a list of roles and users with View permission. Used to filter out items you're not allowed to see. """ allowed = {} for r in rolesForPermissionOn('View', obj): allowed[r] = 1 # shortcut roles and only index the most basic system role if the object # is viewable by either of those if 'Anonymous' in allowed: return ['Anonymous'] elif 'Authenticated' in allowed: return ['Authenticated'] localroles = {} try: acl_users = getToolByName(obj, 'acl_users', None) if acl_users is not None: localroles = acl_users._getAllLocalRoles(obj) except AttributeError: localroles = _mergedLocalRoles(obj) for user, roles in localroles.items(): for role in roles: if role in allowed: allowed['user:'******'Owner' in allowed: del allowed['Owner'] return list(allowed.keys())
def checkPermission(self, permission, object, context): if permission == 'forbidden permission': return 0 roles = rolesForPermissionOn(permission, object) if isinstance(roles, basestring): roles = [roles] return context.user.allowed(object, roles)
def _checkPermission(permission, obj, StringType = type('')): roles = rolesForPermissionOn(permission, obj) if type(roles) is StringType: roles=[roles] if _getAuthenticatedUser( obj ).allowed( obj, roles ): return 1 return 0
def set_permissions(self, obj, new_groups): roles = list(rolesForPermissionOn(self.permission_to_manage, obj)) roles.sort() if 'Viewer' not in obj.__ac_roles__: obj._addRole('Viewer') if 'Viewer' not in roles: roles.append('Viewer') obj.manage_permission(self.permission_to_manage, roles) for group in obj.groups_with_local_role('Viewer'): roles = list(obj.get_local_roles_for_groupid(group)) roles.remove('Viewer') if roles: obj.manage_setLocalGroupRoles(group, roles) else: obj.manage_delLocalGroupRoles((group, )) for group in new_groups: roles = obj.get_local_roles_for_groupid(group) if 'Viewer' not in roles: roles = list(roles) roles.append('Viewer') obj.manage_setLocalGroupRoles(group, roles)
def set_permissions(self, obj, new_groups): roles = list(rolesForPermissionOn(self.permission_to_manage, obj)) roles.sort() if 'Viewer' not in obj.__ac_roles__: obj._addRole('Viewer') if 'Viewer' not in roles: roles.append('Viewer') obj.manage_permission(self.permission_to_manage, roles) for group in obj.groups_with_local_role('Viewer'): roles = list(obj.get_local_roles_for_groupid(group)) roles.remove('Viewer') if roles: obj.manage_setLocalGroupRoles(group, roles) else: obj.manage_delLocalGroupRoles((group,)) for group in new_groups: roles = obj.get_local_roles_for_groupid(group) if 'Viewer' not in roles: roles = list(roles) roles.append('Viewer') obj.manage_setLocalGroupRoles(group, roles)
def checkPermission(self, permission, object, context): if permission == 'forbidden permission': return 0 roles = rolesForPermissionOn(permission, object) if type(roles) in (StringType, UnicodeType): roles=[roles] return context.user.allowed(object, roles)
def xform_data(self, datacontainer, form): if form.has_key(self.id): roles = form[self.id] if type(roles) == types.StringType: roles = [roles] else: id = form.get('id', None) # if we have an ID, we should be dealing with the real object # rather than it's container if id: obj = getattr(datacontainer, id) else: obj = datacontainer roles = rolesForPermissionOn(self.permission_to_manage, obj) # we remove the Manager role, because we should never be adding/removing # it try: roles.remove('Manager') roles.remove('Owner') except: pass f = """<%s>%s</%s>""" % (self.id, ' '.join(roles), self.id) return f
def _checkPermission(permission, obj): """ Check if the current user has the permission on the given object. """ # this code is ported from ZopeSecurityPolicy.checkPermission roles = rolesForPermissionOn(permission, obj) if isinstance(roles, basestring): roles = [roles] context = getSecurityManager()._context # check executable owner and proxy roles # this code is ported from ZopeSecurityPolicy.validate stack = context.stack if stack: eo = stack[-1] owner = eo.getOwner() if owner is not None: if not owner.allowed(obj, roles): return 0 proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: if obj is not aq_base(obj): if not owner._check_context(obj): return 0 for r in proxy_roles: if r in roles: return 1 return 0 return context.user.allowed(obj, roles)
def getRoles(container, name, value, default): global rolesForPermissionOn roles = getattr(value, '__roles__', _noroles) if roles is _noroles: if not name or not type(name) in (str, unicode): return default if type(value) is MethodType: container = value.im_self cls = getattr(container, '__class__', None) if cls is None: return default roles = getattr(cls, '%s__roles__'%name, _noroles) if roles is _noroles: return default value = container if roles is None or type(roles) in tuple_or_list: return roles rolesForPermissionOn = getattr(roles, 'rolesForPermissionOn', None) if rolesForPermissionOn is not None: roles = rolesForPermissionOn(value) return roles
def create_content(self): # We can only initiate if the image is publicly visible if 'Anonymous' not in rolesForPermissionOn('View', self.context): # Reset self.ready = None self.id = None return image_url = self.image_url is_local = '://localhost:' in image_url or '://127.' in image_url if DEBUG and is_local: image_url = SAMPLE_DEBUG_IMAGE elif is_local: return if self.ready: # Updating an already processed image, we need to force a # new URL (and avoid possible front-end caches) image_url = '%s?cachebust=%s'%(image_url, time.time()) request = urllib2.Request('%s?url=%s'%(ZOOMIT_UPLOAD_URL, quote_plus(image_url)), headers={"Accept" : "application/json"}) try: response = opener.open(request) except urllib2.HTTPError, response: pass
def checkPermission(self, permission, object, context): if permission == 'forbidden permission': return 0 roles = rolesForPermissionOn(permission, object) if type(roles) in (StringType, UnicodeType): roles = [roles] return context.user.allowed(object, roles)
def verifyPermission(permission, obj): roles = rolesForPermissionOn(permission, obj) if type(roles) is types.StringType: roles = [roles] # C implementation of validate does not take keyword arguments accessed, container, name, value = obj, obj, '', obj getSecurityManager().validate(accessed, container, name, value, roles)
def allowedRolesAndUsers(obj): """Return a list of roles and users with View permission. Used to filter out items you're not allowed to see. """ allowed = {} for r in rolesForPermissionOn('View', obj): allowed[r] = 1 # shortcut roles and only index the most basic system role if the object # is viewable by either of those if 'Anonymous' in allowed: return ['Anonymous'] elif 'Authenticated' in allowed: return ['Authenticated'] try: acl_users = getToolByName(obj, 'acl_users', None) if acl_users is not None: localroles = acl_users._getAllLocalRoles(obj) except AttributeError: localroles = _mergedLocalRoles(obj) for user, roles in localroles.items(): for role in roles: if role in allowed: allowed['user:'******'Owner' in allowed: del allowed['Owner'] return list(allowed.keys())
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
def groupAddedHandler(groupFolder, event): assert IGSGroupMarker.providedBy(groupFolder), \ "groupFolder did not implement IGSGroupFolder!" site_root = groupFolder.site_root() if site_root.getId() == 'edem': # add a participant ID groupFolder.manage_addProperty('ptn_coach_id', '', 'string') # add a charter, copying it from the template assert hasattr(site_root, "Content"), "site_root has no Content folder" assert hasattr(site_root.Content, "main"), "Content has no main folder" assert hasattr(site_root.Content.main, "charter"), \ "main has no charter folder" charter = getattr(site_root.Content.main, "charter") groupFolder.manage_clone(charter, to_ascii("charter")) # make sure GroupAdmins can manage the properties of the group roles = [] for set in groupFolder.rolesOfPermission('Manage properties'): if set['selected']: roles.append(set['name']) roles = list(rolesForPermissionOn('Manage properties', groupFolder)) if 'GroupAdmin' not in roles: roles.append('GroupAdmin') groupFolder.manage_permission('Manage properties', roles, 1) return
def allowedRolesAndUsers(obj): """Return a list of roles and users with View permission. Used to filter out items you're not allowed to see. """ # 'Access contents information' is the correct permission for # accessing and displaying metadata of an item. # 'View' should be reserved for accessing the item itself. allowed = set(rolesForPermissionOn('Access contents information', obj)) # shortcut roles and only index the most basic system role if the object # is viewable by either of those if 'Anonymous' in allowed: return ['Anonymous'] elif 'Authenticated' in allowed: return ['Authenticated'] localroles = {} try: acl_users = getToolByName(obj, 'acl_users', None) if acl_users is not None: localroles = acl_users._getAllLocalRoles(obj) except AttributeError: localroles = _mergedLocalRoles(obj) for user, roles in localroles.items(): if allowed.intersection(roles): allowed.update(['user:'******'Owner' in allowed: allowed.remove('Owner') return list(allowed)
def rolesForPermission(self, permit): """ return list of roles for permission, ready to use in permissions configlet """ portal = getToolByName(self, 'portal_url').getPortalObject() livePermits = rolesForPermissionOn(permit, portal) myPermits = list(self.getPfgPermissions()) index = myPermits.index(permit) rpos = 0 res = [] for role in portal.rolesOfPermission(permit): name = role['name'] if name not in ['Anonymous', 'Authenticated']: id = "p%dr%d" % (index, rpos) if name in livePermits: checked = 'CHECKED' else: checked = None res.append({ 'label': name, 'id': id, 'checked': checked, }) rpos += 1 return res
def verifyPermission(permission, obj): roles = rolesForPermissionOn(permission, obj) if type(roles) is types.StringType: roles=[roles] # C implementation of validate does not take keyword arguments accessed, container, name, value = obj, obj, '', obj getSecurityManager().validate(accessed, container, name, value, roles)
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
def test_undo(self): wftool = self.site.portal_workflow wf1, wf2 = self._getDummyWorkflows() dummy = self.site._setObject('dummy', DummyContent()) # These are the roles we know about self.assertEquals(['Anonymous', 'Authenticated', 'Manager', 'Owner'], sorted(dummy.validRoles())) self.assertEqual(wf1._getStatusOf(dummy), {'state': 'private', 'comments': ''}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'nonconfidential', 'comments': ''}) # When private and non-confidential, manager and owner have the permission self.assertEquals(['Manager', 'Owner'], sorted(rolesForPermissionOn('View', dummy))) # Let's make it confidential too wftool.doActionFor(dummy, 'make_confidential', comment='bar') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'private', 'comments': ''}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': 'bar'}) # If we now publish it, the result should be the same as if we'd # published first and then made wftool.doActionFor(dummy, 'publish', comment='foo') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'published', 'comments': 'foo'} ) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': 'bar'}) self.assertEquals(['Manager', 'Owner'], sorted(rolesForPermissionOn('View', dummy))) # Now let's make it non-confidential. The result should be the same # as if it was published wftool.doActionFor(dummy, 'make_non_confidential', comment='baz') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'published', 'comments': 'foo'}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'nonconfidential', 'comments': 'baz'}) self.assertEqual(['Anonymous'], sorted(rolesForPermissionOn('View', dummy)))
def visibleToRole(published, role, permission='View'): """Determine if the published object would be visible to the given role. ``role`` is a role name, e.g. ``Anonymous``. ``permission`` is the permission to check for. """ return role in rolesForPermissionOn(permission, published)
def visibleToRole(published, role, permission='View'): """Determine if the published object would be visible to the given role. ``role`` is a role name, e.g. ``Anonymous``. ``permission`` is the permission to check for. """ return role in rolesForPermissionOn(permission, published)
def test_expected_permissions(self): """This integration test shows that the correct permissions were assigned to the Site Administrator role (whether inherited from the Zope application, or specified in the portal rolemap). """ site = self.portal perm = 'Add portal events' role = 'Site Administrator' self.assertTrue(role in rolesForPermissionOn(perm, site))
def checkPermission(self, permission, object, context): if permission == "forbidden permission": return 0 if permission == "addFoo": return context.user.allowed(object, ["FooAdder"]) roles = rolesForPermissionOn(permission, object) if isinstance(roles, basestring): roles = [roles] return context.user.allowed(object, roles)
def test_with_permissions_reacts(self): wftool = self.site.portal_workflow wf1, wf2 = self._getDummyWorkflows() dummy = self.site._setObject('dummy', DummyContent()) # setting the object will notify an AddedObjectEvent, which call # Products.CMFCore.CMFCatalogAware.handleContentishEvent which call # ob.notifyWorkflowCreated() which call wftool.notifyCreated(ob) # which notify AfterTransitionEvent for wf1, and then for wf2. # event.transition is None, but we want to execute the code of react.object_transitioned # in the case of confidential state as the initial state # These are the roles we know about self.assertEquals(['Anonymous', 'Authenticated', 'Manager', 'Owner'], sorted(dummy.validRoles())) # wftool.notifyCreated(dummy) self.assertEqual(wf1._getStatusOf(dummy), {'state': 'private', 'comments': ''}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'nonconfidential', 'comments': ''}) # When private and non-confidential, manager and owner have the permission self.assertEqual(['Manager', 'Owner'], sorted(rolesForPermissionOn('View', dummy))) # Let's make it confidential too wftool.doActionFor(dummy, 'make_confidential', comment='bar') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'private', 'comments': ''}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': 'bar'}) # If we now publish it, the result should be the same as if we'd # published first and then made wftool.doActionFor(dummy, 'publish', comment='foo') self.assertEqual(wf1._getStatusOf(dummy), {'state': 'published', 'comments': 'foo'}) self.assertEqual(wf2._getStatusOf(dummy), {'state': 'confidential', 'comments': 'bar'}) self.assertEquals(['Manager', 'Owner'], sorted(rolesForPermissionOn('View', dummy)))
def get_visibility(instance): retval = PERM_ODD roles = rolesForPermissionOn('View', instance) if (('Anonymous' in roles) and ('Authenticated' in roles)): retval = PERM_ANN elif ('GroupMember' in roles): retval = PERM_GRP assert type(retval) == int assert retval in (PERM_ODD, PERM_ANN, PERM_GRP) return retval
def get_visibility(instance): retval = PERM_ODD roles = rolesForPermissionOn('View', instance) if (('Anonymous' in roles) and ('Authenticated' in roles)): retval = PERM_ANN elif ('GroupMember' in roles): retval = PERM_GRP assert type(retval) == int assert retval in (PERM_ODD, PERM_ANN, PERM_GRP) return retval
def has_permission(self, permission, object): """Check if the user has a permission on an object. This method is just for inspecting permission settings. For access control use getSecurityManager().checkPermission() instead. """ roles = rolesForPermissionOn(permission, object) if isinstance(roles, str): roles = [roles] return self.allowed(object, roles)
def has_permission(self, permission, object): """Check if the user has a permission on an object. This method is just for inspecting permission settings. For access control use getSecurityManager().checkPermission() instead. """ roles = rolesForPermissionOn(permission, object) if isinstance(roles, str): roles = [roles] return self.allowed(object, roles)
def checkGuard(guard, ob): # returns 1 if guard passes against ob, else 0. # TODO : implement TALES evaluation by defining an appropriate # context. u_roles = None def getRoles(): sm = getSecurityManager() u = sm.getUser() stack = sm._context.stack if stack and len(stack) > 1: eo = stack[-2] # -1 is the current script. proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: roles = proxy_roles return proxy_roles roles = u.getRolesInContext(ob) return roles if guard.permissions: # Require at least one role for required roles for the given permission. if u_roles is None: u_roles = getRoles() for p in guard.permissions: if set(rolesForPermissionOn(p, ob)).intersection(u_roles): break else: return 0 if guard.roles: # Require at least one of the given roles. if u_roles is None: u_roles = getRoles() for role in guard.roles: if role in u_roles: break else: return 0 if guard.groups: # Require at least one of the specified groups. sm = getSecurityManager() u = sm.getUser() b = aq_base(u) if hasattr(b, 'getGroupsInContext'): u_groups = u.getGroupsInContext(ob) elif hasattr(b, 'getGroups'): u_groups = u.getGroups() else: u_groups = () for group in guard.groups: if group in u_groups: break else: return 0 return 1
def get_principals(self): # index the principal which have View permission. This is according to # the allowedRolesAndUsers index but it does not car of global roles. allowed_roles = rolesForPermissionOn(View, self) principals = [] for principal, roles in _mergedLocalRoles(self).items(): for role in roles: if role in allowed_roles: principals.append(safe_unicode(principal)) break return principals
def get_roles_for_permission(permission, brain_or_object): """Get a list of granted roles for the given permission on the object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Roles for the given Permission :rtype: list """ obj = get_object(brain_or_object) allowed = set(rolesForPermissionOn(permission, obj)) return sorted(allowed)
def allowedRolesAndUsers(context): allowed = set() for r in rolesForPermissionOn("View", context): allowed.add(r) for user, roles in _mergedLocalRoles(context).iteritems(): for role in roles: if role in allowed: allowed.add('user:'******'Owner' in allowed: allowed.remove('Owner') return list(allowed)
def allowedRolesAndUsers(context): allowed = set() for r in rolesForPermissionOn("View", context): allowed.add(r) for user, roles in _mergedLocalRoles(context).iteritems(): for role in roles: if role in allowed: allowed.add('user:'******'Owner' in allowed: allowed.remove('Owner') return list(allowed)
def get_principals(self): # index the principal which have View permission. This is according to # the allowedRolesAndUsers index but it does not car of global roles. allowed_roles = rolesForPermissionOn(View, self) principals = [] for principal, roles in _mergedLocalRoles(self).items(): for role in roles: if role in allowed_roles: principals.append(safe_unicode(principal)) break return principals
def get_roles_for_permission(permission, brain_or_object): """Get a list of granted roles for the given permission on the object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Roles for the given Permission :rtype: list """ obj = get_object(brain_or_object) allowed = set(rolesForPermissionOn(permission, obj)) return sorted(allowed)
def _available_for_anonymous(obj): """ Checks if object is available for anonymous users """ chain = obj.aq_chain # is object and its parents are available for anonymous? for subobj in chain: if IBaseObject.providedBy(subobj) or isinstance(subobj, PloneSite): if not "Anonymous" in rolesForPermissionOn("View", subobj): return False return True
def test13TestCMFLRBehaviour(self,): """Special test to check that CMF's allowedRolesAndUsers is okay """ # Allowed patterns normal_allowed = ['r1', 'r2', 'r3', 'user:group_g1', 'user:u6', 'user:u3'] normal_allowed.sort() blocked_allowed = ["r1", "r2", "r3", "user:u3", "user:u6", ] blocked_allowed.sort() # Normal behaviour ob = self.subsublr2 allowed = {} for r in rolesForPermissionOn('View', ob): allowed[r] = 1 localroles = _mergedLocalRoles(ob) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] allowed = list(allowed.keys()) allowed.sort() self.failUnlessEqual(allowed, normal_allowed) # LR-blocking behaviour self.gruf._acquireLocalRoles(self.sublr2, 0) ob = self.subsublr2 allowed = {} for r in rolesForPermissionOn('View', ob): allowed[r] = 1 localroles = _mergedLocalRoles(ob) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] allowed = list(allowed.keys()) allowed.sort() self.failUnlessEqual(allowed, blocked_allowed)
def get_minimum_role(self): roles = filter( lambda r: r in roleinfo.ALL_ROLES, map(str, rolesForPermissionOn( SilvaPermissions.View, self.context))) roles.sort(key=roleinfo.ALL_ROLES.index) if roles: role = roles[0] if role == 'Anonymous': return None return role return None
def __init__(self, instance): roles = rolesForPermissionOn('View', instance) self.anon = 'Anonymous' in roles self.siteMember = 'DivisionMember' in roles self.siteMemberOnly = not(self.anon) and self.siteMember self.groupMemberOnly = not(self.anon or self.siteMember) # --=mpj17=-- I am tempted to assert that the GroupMember has # the view role, but I won't. assert type(self.anon) == bool assert type(self.siteMember) == bool
def allowedRolesAndUsers(self): """ Return a list of roles and users with View permission. Used by PortalCatalog to filter out items you're not allowed to see. """ ob = self.__ob allowed = {} for r in rolesForPermissionOn(View, ob): allowed[r] = 1 localroles = _mergedLocalRoles(ob) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] return list(allowed.keys())
def set_permissions(self, obj, new_roles, assume_acquire=True): roles = list(rolesForPermissionOn(self.permission_to_manage, obj)) new_roles = list(new_roles) roles.sort() new_roles.sort() # if assume_acquire is set, we assume that if the new_roles match # the existing roles, we are wanting to keep getting those roles via # acquisition, or at least, that we shouldn't do anything if assume_acquire and roles == new_roles: return # We _always_ want the Manager, Owner and Viewer roles added, # otherwise we might never get indexed, and group management won't work! new_roles.append('Manager') new_roles.append('Owner') new_roles.append('Viewer') obj.manage_permission(self.permission_to_manage, new_roles)
def triggerSiteimproveRecheck(obj, event): """ Sets cookie 'flag' to indicate that a recheck needs to take place """ if ICollectiveSiteimproveLayer.providedBy(getRequest()): recheck = False if IObjectModifiedEvent.providedBy(event) and \ 'Anonymous' in rolesForPermissionOn('View', event.object): # object saved and publically visible recheck = True elif IActionSucceededEvent.providedBy(event): # workflow transition recheck = True if recheck: request = getRequest() expiration_seconds = time.time() + (1 * 60 * 60) # 1 hour from now expires = formatdate(expiration_seconds, usegmt=True) request.response.setCookie("SI-Published", True, path='/', expires=expires)
def SFAllowedRolesAndUsersModify(obj): """Return a list of roles and users with Modify portal content permission. Used by PortalCatalog to filter out items you're not allowed to modify in the calendar. """ allowed = {} for r in rolesForPermissionOn('Modify portal content', obj): allowed[r] = 1 try: acl_users = getToolByName(obj, 'acl_users') localroles = acl_users._getAllLocalRoles(obj) except AttributeError: localroles = _mergedLocalRoles(obj) for user, roles in localroles.items(): for role in roles: if allowed.has_key(role): allowed['user:'******'Owner'): del allowed['Owner'] return list(allowed.keys())
def get_visibility(instance): '''Get the visibility for an object. :param object instance: An instance of an object :returns: The visibility of the object. It will be one of :const:`PERM_ODD`, :const:`PERM_ANN`, :const:`PERM_GRP`, or :const:`PERM_SIT`. :rtype: int The :func:`.get_visibility` function wraps the even-lower :func:`AccessControl.PermissionRole.rolesForPermissionOn` function to determine who can see an object.''' retval = PERM_ODD roles = rolesForPermissionOn('View', instance) if (('Anonymous' in roles) and ('Authenticated' in roles)): retval = PERM_ANN elif ('DivisionMember' in roles): retval = PERM_SIT elif ('GroupMember' in roles): retval = PERM_GRP assert type(retval) == int assert retval in (PERM_ODD, PERM_ANN, PERM_SIT, PERM_GRP) return retval
def _checkGuard(guard, ob): # returns 1 if guard passes against ob, else 0. # TODO : implement TALES evaluation by defining an appropriate # context. if guard.permissions: # Require at least one role for required roles for the given permission. u_roles = getRoles(ob) for p in guard.permissions: if not u_roles.isdisjoint(rolesForPermissionOn(p, ob)): break else: return 0 else: u_roles = None if guard.roles: # Require at least one of the given roles. if u_roles is None: u_roles = getRoles(ob) if u_roles.isdisjoint(guard.roles): return 0 if guard.groups: # Require at least one of the specified groups. sm = getSecurityManager() u = sm.getUser() b = aq_base(u) if hasattr(b, 'getGroupsInContext'): u_groups = u.getGroupsInContext(ob) elif hasattr(b, 'getGroups'): u_groups = u.getGroups() else: u_groups = () for group in guard.groups: if group in u_groups: break else: return 0 return 1