def roles_of_permission(context, permission): """Return all roles which have the given permission on the current context.""" role_manager = IRoleManager(context) for p in role_manager.ac_inherited_permissions(1): name, value = p[:2] if name == permission: p = Permission(name, value, role_manager) roles = p.getRoles() return roles
def __iter__(self): for item in self.previous: if '_username' in item.keys(): member = self.memtool.getMemberById(item['_username']) if not member: yield item; continue member.setMemberProperties(item['_properties']) # add member to group if item.get('_user_groups', False): for groupid in item['_user_groups']: group = self.gtool.getGroupById(groupid) if group: group.addMember(item['_username']) # setting global roles if item.get('_root_roles', False): self.portal.acl_users.userFolderEditUser( item['_username'], None, item['_root_roles']) # setting local roles if item.get('_local_roles', False): try: obj = self.portal.unrestrictedTraverse(item['_plone_site']) except (AttributeError, KeyError): pass else: if IRoleManager.providedBy(obj): obj.manage_addLocalRoles(item['_username'], item['_local_roles']) obj.reindexObjectSecurity() yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*list(item.keys()))[0] roleskey = self.roleskey(*list(item.keys()))[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item continue path = safe_unicode(item[pathkey].lstrip('/')).encode('ascii') obj = traverse(self.context, path, None) # path doesn't exist if obj is None: yield item continue if IRoleManager.providedBy(obj): for principal, roles in list(item[roleskey].items()): if roles: obj.manage_addLocalRoles(principal, roles) obj.reindexObjectSecurity() yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] roleskey = self.roleskey(*item.keys())[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item continue path = safe_unicode(item[pathkey].lstrip('/')).encode('ascii') obj = traverse(self.context, path, None) # path doesn't exist if obj is None: yield item continue if IRoleManager.providedBy(obj): for principal, roles in item[roleskey].items(): if roles: obj.manage_addLocalRoles(principal, roles) obj.reindexObjectSecurity() yield item
def setReviewer(issue, event): log( "=== Default Reviewer Role Attribution in Issue ===") acl_users = getToolByName(issue, 'acl_users') mail_host = getToolByName(issue, 'MailHost') portal_url = getToolByName(issue, 'portal_url') parent = issue.aq_inner.aq_parent log( parent.__name__ + "parent local roles : " +str(parent.get_local_roles()) + "\naq_parent'parent local roles : " + str(parent.aq_parent.get_local_roles())) users_with_the_role = [] if parent.Type() == "Tracker": log( "Testing parent's reviewers") users_roles = parent.get_local_roles() log("users roles : " + str( users_roles)) users_with_the_role = [x[0] for x in users_roles if 'Reviewer' in x[1]] for member in users_with_the_role: log("member : " + member) #Add local roles to a group if IRoleManager.providedBy(issue): for member in users_with_the_role: log( "adding roles (Reviewer) to " + member ) issue.manage_addLocalRoles(member, ['Reviewer']) return
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] permskey = self.permskey(*item.keys())[0] if not pathkey or not permskey or \ permskey not in item: # not enough info yield item continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item continue if IRoleManager.providedBy(obj): for perm, perm_dict in item[permskey].items(): try: obj.manage_permission(perm, roles=perm_dict['roles'], acquire=perm_dict['acquire']) except ValueError: # raise Exception('Error setting the perm "%s"' % perm) logger.error('Error setting the perm "%s" on %s' % (perm, item[pathkey])) yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] permskey = self.permskey(*item.keys())[0] if not pathkey or not permskey or \ permskey not in item: # not enough info yield item; continue obj = self.context.unrestrictedTraverse( item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item; continue if IRoleManager.providedBy(obj): for perm, perm_dict in item[permskey].items(): try: obj.manage_permission(perm, roles=perm_dict['roles'], acquire=perm_dict['acquire']) except ValueError: #raise Exception('Error setting the perm "%s"' % perm) logger.error('Error setting the perm "%s" on %s' % (perm, item[pathkey])) yield item
def createGroup(projet, event): print "=== Group creation ===" acl_users = getToolByName(projet, 'acl_users') mail_host = getToolByName(projet, 'MailHost') portal_url = getToolByName(projet, 'portal_url') portal = portal_url.getPortalObject() sender = portal.getProperty('email_from_address') gr = portal.portal_groups group_id = projet.id if not group_id in gr.getGroupIds(): gr.addGroup(group_id) for member in projet.contributor: gtool = getToolByName(portal, "portal_groups", None) user_groups = gtool.getGroupsByUserId(member) print "user groups for member %s : "%member, user_groups if group_id not in user_groups: print "adding group ", group_id gr.addPrincipalToGroup(member, group_id) #Add local roles to a group if IRoleManager.providedBy(projet): print "adding roles (contributor and Editor) to ", group_id projet.manage_addLocalRoles(group_id, ['Contributor','Editor']) return
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*list(item.keys()))[0] roleskey = self.roleskey(*list(item.keys()))[0] if (not pathkey or not roleskey or roleskey not in item): # not enough info yield item continue obj = self.context.unrestrictedTraverse( str(item[pathkey]).lstrip("/"), None) if obj is None: # path doesn't exist yield item continue if IRoleManager.providedBy(obj): for principal, roles in item[roleskey].items(): if roles: obj.manage_addLocalRoles(principal, roles) try: obj.reindexObjectSecurity() except Exception: logger.warning( "Failed to reindexObjectSecurity {}".format( item["_path"])) yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] roleskey = self.roleskey(*item.keys())[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item; continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item; continue if IRoleManager.providedBy(obj): if self.options.get('erasebefore'): obj.__ac_local_roles__ = {} for principal, roles in item[roleskey].items(): if roles: if principal.startswith(u'group_'): principal = idnormalizer.normalize(principal) obj.manage_addLocalRoles(principal, roles) obj.reindexObjectSecurity() yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*list(item.keys()))[0] permskey = self.permskey(*list(item.keys()))[0] if not pathkey or not permskey or \ permskey not in item: # not enough info yield item continue path = safe_unicode(item[pathkey].lstrip('/')).encode('ascii') obj = traverse(self.context, path, None) if obj is None: yield item continue if IRoleManager.providedBy(obj): for perm, perm_dict in list(item[permskey].items()): try: obj.manage_permission(perm, roles=perm_dict['roles'], acquire=perm_dict['acquire']) except ValueError: # raise Exception('Error setting the perm "%s"' % perm) logger.error('Error setting the perm "%s" on %s' % (perm, item[pathkey])) yield item
def agregaRolesAGrupo(contexto,groupid,listRoles): """Agrega un grupoid con los roles en listRoles a una carpeta""" for gs in contexto.aq_base.get_local_roles(): if gs[0]==groupid: return if IRoleManager.providedBy(contexto): contexto.aq_base.manage_addLocalRoles(groupid, listRoles)
def configure_development_options(self): for obj in self.site.listFolderContents(): if not IRoleManager.providedBy(obj): continue if self._has_default_role_assignments(obj): self._assign_roles_to_development_users_group( ["Contributor", "Editor", "Reader"], obj) elif self._has_meeting_role_assignments(obj): self._assign_roles_to_development_users_group( ["CommitteeAdministrator"], obj)
def checkWorkspacePermission(self): helper = zope.component.queryAdapter( self.context, IExposureSourceAdapter) exposure, workspace, path = helper.source() if not IRoleManager.providedBy(workspace): # We don't know? return False for i in workspace.rolesOfPermission('View'): if i['name'] == 'Anonymous': return i['selected']
def reply(self): serializer = queryMultiAdapter((self.context, self.request), ISerializeToJson) if serializer is None: self.request.response.setStatus(501) return dict(error=dict(message='No serializer available.')) data = serializer() if IRoleManager.providedBy(self.context): data['sharing'] = { '@id': '{}/@sharing'.format(self.context.absolute_url()), 'title': 'Sharing', } return data
def __iter__(self): for item in self.previous: if not item.get('_groupname', False): yield item; continue group = self.gtool.getGroupById(item['_groupname']) if not group: yield item; continue if item.get('_root_group', False): self.gtool.editGroup(item['_groupname'], roles=item['_roles']) elif item.get('_roles', False): # setting local roles try: obj = self.portal.unrestrictedTraverse(item['_plone_site']) except (AttributeError, KeyError): pass else: if IRoleManager.providedBy(obj): obj.manage_addLocalRoles(item['_groupname'], item['_roles']) obj.reindexObjectSecurity() if item.get('_group_groups', False): try: self.gtool.editGroup(item['_groupname'], groups=item.get('_group_groups', [])) except: pass # With PlonePAS > 4.0b3, mutable_properties.enumerateUsers doesn't # return groups anymore, so it isn't possible to search a group # by its title stored in mutable_properties. Only the # title in source_groups is searched. # editGroup modify the title and description in source_groups # plugin, then it calls setGroupProperties(kw) which set the # properties on the mutable_properties plugin. if '_properties' in item: self.gtool.editGroup(item['_groupname'], **item['_properties']) yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] roleskey = self.roleskey(*item.keys())[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item; continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item; continue if IRoleManager.providedBy(obj): for principal, roles in item[roleskey].items(): if roles: obj.manage_addLocalRoles(principal, roles) obj.reindexObjectSecurity() yield item
def createGroup(projet, event): acl_users = getToolByName(projet, 'acl_users') mail_host = getToolByName(projet, 'MailHost') portal_url = getToolByName(projet, 'portal_url') catalog = getToolByName(projet, 'portal_catalog') portal = portal_url.getPortalObject() gr = portal.portal_groups group_id = projet.id log("=== Group creation ===> " + group_id) group = gr.getGroupById(group_id) if not group: gr.addGroup(group_id) group = gr.getGroupById(group_id) admid = 'admin_%s'%projet.id adm = projet[admid] projectPath = projet.absolute_url() #members = adm.objectIds(['ageliaco.rd.auteur']) => filter ne marche pas avec Dexterity members = adm.objectValues() #=> filtre sur le type ne marche pas avec Dexterity for member in members: if member.portal_type == 'ageliaco.rd.auteur': gr.addPrincipalToGroup(member.id, group_id) # gtool = getToolByName(portal, "portal_groups", None) # user_groups = gtool.getGroupsByUserId(member) # print "user groups for member %s : "%member, user_groups # if group_id not in user_groups: # print "adding group ", group_id # gr.addPrincipalToGroup(member.id, group_id) #Add local roles to a group if IRoleManager.providedBy(projet): log("adding roles (contributor and Editor) to " + group_id) projet.manage_addLocalRoles(group_id, ['Contributor','Editor']) return
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] roleskey = self.roleskey(*item.keys())[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item; continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item; continue if IRoleManager.providedBy(obj): new_settings = [] groups = getToolByName(self.context, 'portal_groups') newrolemap = self.options.get('local-roles-mapping', {}) if newrolemap: newrolemap = newrolemap.split('\n') newrolemap = dict([(t.split(':')[0].strip(), t.split(':')[1].strip()) for t in newrolemap if ':' in t]) for principal, roles in item[roleskey].items(): if roles: if newrolemap: roles = [newrolemap.get(r, r) for r in roles] obj.manage_addLocalRoles(principal, roles) obj.reindexObjectSecurity() if HAS_GS: new_settings.append({ 'id': principal, 'type': groups.getGroupById(principal) and 'group' or 'user', 'roles': [r for r in roles if queryUtility(IRolesPageRole, r)], }) if HAS_GS and ILocalGroupSpacePASRoles.providedBy(obj): roles_view = RolesView(obj, TestRequest()) roles_view.update_role_settings(new_settings) yield item
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] roleskey = self.roleskey(*item.keys())[0] if not pathkey or not roleskey or \ roleskey not in item: # not enough info yield item continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item continue if IRoleManager.providedBy(obj): for principal, roles in item[roleskey].items(): if roles: RoleAssignmentManager(obj).add_or_update_assignment( SharingRoleAssignment(principal, roles)) yield item
def _assign_local_roles_to_managers(self, ml): assign_local_role('Owner', ml.managers, IRoleManager(ml))
def _assign_local_roles_to_managers(self): ml = self.context assign_local_role('Owner', ml.managers, IRoleManager(ml))
def update(self): # Allow the source to provide terms until we have more specific ones # from the query. Things do not go well if self.terms is None self._bound_source = None source = self.bound_source self.terms = SourceTerms(self.context, self.request, self.form, self.field, self, source) # If we have values in the request, use these to get the terms. # Otherwise, take the value from the current saved value. terms = [] request_values = z3c.form.interfaces.NOVALUE if not self.ignoreRequest: request_values = self.extract(default=z3c.form.interfaces.NOVALUE) if request_values is not z3c.form.interfaces.NOVALUE: if not isinstance(request_values, (tuple, set, list)): request_values = (request_values,) for token in request_values: if not token or token == self.noValueToken: continue try: terms.append(source.getTermByToken(token)) except LookupError: # Term no longer available if not self.ignoreMissing: raise elif not self.ignoreContext: selection = zope.component.getMultiAdapter( (self.context, self.field), z3c.form.interfaces.IDataManager).query() if selection is z3c.form.interfaces.NOVALUE: selection = [] elif not isinstance(selection, (tuple, set, list)): selection = [selection] for value in selection: if not value: continue if HAS_AC and IRoleManager.providedBy(value): if not checkPermission('zope2.View', value): continue try: terms.append(source.getTerm(value)) except LookupError: # Term no longer available if not self.ignoreMissing: raise # Set up query form subform = self.subform = QuerySubForm(QueryContext(), self.request, self.name) subform.update() # Don't carry on any search if we're ignoring the request if not self.ignoreRequest: data, errors = subform.extractData() if errors: return # perform the search query = data['query'] if query is not None: query_terms = set(source.search(query)) tokens = set([term.token for term in terms]) for term in query_terms: if term.token not in tokens: terms.append(term) # set terms self.terms = QueryTerms(self.context, self.request, self.form, self.field, self, terms) # update widget - will set self.value self.updateQueryWidget() # add "novalue" option if self._radio and not self.required: self.items.insert(0, { 'id': self.id + '-novalue', 'name': self.name + ':list', 'value': self.noValueToken, 'label': self.noValueLabel, 'checked': not self.value or self.value[0] == self.noValueToken, })
def getMostVisitedContent(self): site = getSite() site_url = site.absolute_url() r = redis.StrictRedis(host='localhost', port=6379, db=0) pipe = r.pipeline() timeslot = time.time() // 3600 for hour in range(self.data.hours + 1): # We need to get all results, so we can filter out amount = r.zcard('tophits.%s' % (timeslot-hour)) pipe.zrevrange('tophits.%s' % (timeslot-hour), 0, amount, withscores=True, score_cast_func=int) redis_results = pipe.execute() partial_results = {} for hour_result in redis_results: for result in hour_result: if result[0].endswith('.css') or\ result[0].endswith('.kss') or\ result[0].endswith('.gif') or\ result[0].endswith('.js'): # We have a resource, just ignore it continue count = partial_results.get(result[0], 0) count += result[1] partial_results[result[0]] = count # Filter out resources results = [] for i in partial_results: if len(results) == self.data.max_results: # If we already have all results we need, then get out of loop break # We have a candidate, get the relative path rel_path = i[len(site_url)+1:] # Now let's get the proper object try: obj = site.restrictedTraverse(rel_path) except AttributeError: # Invalid resource. Ignore continue except KeyError: # Invalid resource. Ignore continue except NotFound: # Resource not found. Ignore continue except TypeError: # Invalid resource. Ignore continue except IndexError: # Invalid resource. Ignore continue # Let's check, we actually have a CT # XXX: Not sure which interface to use here. It should be common # to AT and Dexterity types if not IRoleManager.providedBy(obj): continue # Finally, let's check that this object is of the type we # want if obj.portal_type in self.data.types: # Yeah ! append it to the results # XXX: Shall we store the hit number ? we will for now... results.append((obj, partial_results[i])) # Now, sort it using the number of hits results.sort(key=lambda x:x[1], reverse=True) return results
def configure_development_options(self): for obj in self.site.listFolderContents(): if IRoleManager.providedBy(obj): obj.manage_addLocalRoles( DEVELOPMENT_USERS_GROUP, ["Contributor", "Editor", "Reader"])
def configure_development_options(self): for obj in self.site.listFolderContents(): if IRoleManager.providedBy( obj) and not IPrivateRoot.providedBy(obj): obj.manage_addLocalRoles(DEVELOPMENT_USERS_GROUP, ["Contributor", "Editor", "Reader"])
def update(self): # Allow the source to provide terms until we have more specific ones # from the query. Things do not go well if self.terms is None self._bound_source = None source = self.bound_source self.terms = SourceTerms(self.context, self.request, self.form, self.field, self, source) # If we have values in the request, use these to get the terms. # Otherwise, take the value from the current saved value. terms = [] request_values = z3c.form.interfaces.NOVALUE if not self.ignoreRequest: request_values = self.extract(default=z3c.form.interfaces.NOVALUE) if request_values is not z3c.form.interfaces.NOVALUE: if not isinstance(request_values, (tuple, set, list)): request_values = (request_values, ) for token in request_values: if not token or token == self.noValueToken: continue try: terms.append(source.getTermByToken(token)) except LookupError: # Term no longer available if not self.ignoreMissing: raise elif not self.ignoreContext: selection = zope.component.getMultiAdapter( (self.context, self.field), z3c.form.interfaces.IDataManager).query() if selection is z3c.form.interfaces.NOVALUE: selection = [] elif not isinstance(selection, (tuple, set, list)): selection = [selection] for value in selection: if not value: continue if HAS_AC and IRoleManager.providedBy(value): if not checkPermission('zope2.View', value): continue try: terms.append(source.getTerm(value)) except LookupError: # Term no longer available if not self.ignoreMissing: raise elif self.showDefault: adapter = zope.component.queryMultiAdapter( (self.context, self.request, self.form, self.field, self), z3c.form.interfaces.IValue, name='default') if adapter: default_value = adapter.get() if not isinstance(default_value, (tuple, set, list)): default_value = [default_value] for value in default_value: if not value: continue if HAS_AC and IRoleManager.providedBy(value): if not checkPermission('zope2.View', value): continue try: terms.append(source.getTerm(value)) except LookupError: # Term no longer available if not self.ignoreMissing: raise # Set up query form subform = self.subform = QuerySubForm(QueryContext(), self.request, self.name) subform.update() # Don't carry on any search if we're ignoring the request if not self.ignoreRequest: data, errors = subform.extractData() if errors: return # perform the search query = data['query'] if query is not None: query_terms = set(source.search(query)) tokens = set([term.token for term in terms]) for term in query_terms: if term.token not in tokens: terms.append(term) # set terms self.terms = QueryTerms(self.context, self.request, self.form, self.field, self, terms) # update widget - will set self.value self.updateQueryWidget()