def group_membership_role_deleted(group_membership_role, event): if group_membership_role.is_global: prm = IPrincipalRoleMap( get_group_context(group_membership_role.member.group)) prm.unsetRoleForPrincipal( group_membership_role.role_id, group_membership_role.member.user.login)
def group_membership_role_added(group_membership_role, event): if group_membership_role.is_global: prm = IPrincipalRoleMap( get_group_context(group_membership_role.member.group)) prm.assignRoleToPrincipal( group_membership_role.role_id, group_membership_role.member.user.login)
def cached_principal_roles(self, parent, principal): cache = self.cache(parent) try: cache_principal_roles = cache.principal_roles except AttributeError: cache_principal_roles = cache.principal_roles = {} try: return cache_principal_roles[principal] except KeyError: pass if parent is None: roles = dict( [(role, SettingAsBoolean[setting]) for (role, setting) in globalRolesForPrincipal(principal)]) roles['zope.Anonymous'] = True # Everybody has Anonymous cache_principal_roles[principal] = roles return roles roles = self.cached_principal_roles( removeSecurityProxy(getattr(parent, '__parent__', None)), principal) prinrole = IPrincipalRoleMap(parent, None) if prinrole: roles = roles.copy() for role, setting in prinrole.getRolesForPrincipal(principal): roles[role] = SettingAsBoolean[setting] cache_principal_roles[principal] = roles return roles
def _set_group_local_role(context, unset=False): def get_group_local_role(group): if interfaces.IParliament.providedBy(group): return "bungeni.MP" elif interfaces.IMinistry.providedBy(group): return "bungeni.Minister" elif interfaces.ICommittee.providedBy(group): return "bungeni.CommitteeMember" elif interfaces.IPoliticalGroup.providedBy(group): return "bungeni.PartyMember" elif interfaces.IGovernment.providedBy(group): return "bungeni.Government" elif interfaces.IOffice.providedBy(group): return group.office_role else: return "bungeni.GroupMember" def get_group_context(context): if interfaces.IOffice.providedBy(context): return BungeniApp() #get_parliament(context) else: return removeSecurityProxy(context) role = get_group_local_role(context) group = removeSecurityProxy(context) ctx = get_group_context(context) prm = IPrincipalRoleMap(ctx) if not unset: prm.assignRoleToPrincipal(role, group.group_principal_id) else: prm.unsetRoleForPrincipal(role, group.group_principal_id)
def __init__(self, context, request): self._assignable_roles = [] self.principal = utils.common.get_request_principal() self.context_roles = common.get_context_roles(context, self.principal) self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) super(UserAssignmentView, self).__init__(context, request)
def __call__(self): try: context = removeSecurityProxy(self.context) map = IPrincipalRoleMap(context) print list(map.getPrincipalsAndRoles()) files = [] path = os.path.join(setupStorageDirectory(), self.context.type) if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path,context.__name__) files.append(file_path+'.xml') with open(file_path+'.xml','w') as file: file.write(serialize(obj2dict(context,1,parent=None,include=['event','versions'],exclude=[]))) if len(context.attached_files) > 0: for attachment in context.attached_files: attachment_path = os.path.join(path, attachment.file_name) files.append(attachment_path) with open(os.path.join(path, attachment.file_name), 'wb') as file: file.write(attachment.file_data) zip = ZipFile(file_path+'.zip', 'w') for file in files: zip.write(file, os.path.split(file)[-1]) os.remove(file) zip.close() return 'Done!' except: traceback.print_exception(*sys.exc_info())
def cached_principal_roles(self, parent, principal): # Redefine it to get global roles cache = self.cache(parent) try: cache_principal_roles = cache.principal_roles except AttributeError: cache_principal_roles = cache.principal_roles = {} try: return cache_principal_roles[principal] except KeyError: pass if parent is None: roles = dict( [(role, SettingAsBoolean[setting]) for (role, setting) in globalRolesForPrincipal(principal)]) roles['plone.Anonymous'] = True # Everybody has Anonymous cache_principal_roles[principal] = roles return roles roles = self.cached_principal_roles( removeSecurityProxy(getattr(parent, '__parent__', None)), principal) prinrole = IPrincipalRoleMap(parent, None) if prinrole: roles = roles.copy() for role, setting in prinrole.getRolesForPrincipal( principal, self.request): roles[role] = SettingAsBoolean[setting] cache_principal_roles[principal] = roles return roles
def __init__(self, context, request): if IDebateTakeContainer.providedBy(context): self.context = removeSecurityProxy(context).__parent__ else: self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) self.request = request
def assign_signatory_role(context, owner_login, unset=False): log.debug("assign signatory role [%s] user: [%s]", context, owner_login) if unset: IPrincipalRoleMap(context).unsetRoleForPrincipal( u"bungeni.Signatory", owner_login) else: IPrincipalRoleMap(context).assignRoleToPrincipal( u"bungeni.Signatory", owner_login)
def _set_group_local_role(context, unset=False): group = context role = get_group_local_role(group) prm = IPrincipalRoleMap(get_group_context(group)) if not unset: prm.assignRoleToPrincipal(role, group.group_principal_id) else: prm.unsetRoleForPrincipal(role, group.group_principal_id)
def _query(self, **kw): principal = get_principal() roles = get_workspace_roles() group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] count = 0 for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status) ) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter( """(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"].lower()) ) # The first page of the results is loaded the most number of times # The limit on the query below optimises for when no filter has # been applied by limiting the number of results returned. if (not kw.get("start", 0) and not kw.get("sort_on", None)): count = count + query.count() query = query.order_by(domain_class.status_date).limit( kw.get("limit", 25)) results.extend(query.all()) object_roles_domain_status = self.item_status_filter(kw, OBJECT_ROLES) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter( """(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"]) ) if (not kw.get("start", 0) and not kw.get("sort_on", None)): count = count + query.count() query = query.order_by(domain_class.status_date).limit( kw.get("limit", 25)) for obj in query.all(): prm = IPrincipalRoleMap(obj) for obj_role in OBJECT_ROLES: if (prm.getSetting(obj_role, principal.id) == Allow and obj not in results): results.append(obj) break # Sort items if (kw.get("sort_on", None) and kw.get("sort_dir", None)): rev = True if (kw.get("sort_dir") == "desc") else False results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=rev) if (kw.get("start", 0) and kw.get("sort_on", None)): count = len(results) return (results, count)
def setBungeniOwner(context): user_id = get_principal_id() if not user_id: user_id = "-" owner_id = getOwnerId(context) log.debug("setBungeniOwner [%s] user_id:%s owner_id:%s" % ( context, user_id, owner_id)) if user_id: IPrincipalRoleMap(context).assignRoleToPrincipal(u'bungeni.Owner', user_id) if owner_id and (owner_id!=user_id): IPrincipalRoleMap(context).assignRoleToPrincipal(u'bungeni.Owner', owner_id)
def _do_save(self, data): group_role_changed = False prm = IPrincipalRoleMap(get_group_privilege_extent_context(self.context)) if (data["group_role"] != self.context.group_role): if prm.getSetting(self.context.group_role, self.context.principal_name) == Allow: group_role_changed = True unset_group_local_role(self.context) formlib.form.applyChanges(self.context, self.form_fields, data) if group_role_changed: set_group_local_role(self.context) notify(ObjectModifiedEvent(self.context))
def get_group_prms(document): prms = [] prms.append(IPrincipalRoleMap(common.get_application())) parent_group = getattr(document, "group", None) if parent_group: prms.append(IPrincipalRoleMap(parent_group)) assigned_groups = getattr(document, "group_assignment", list()) if assigned_groups: for group in assigned_groups: prms.append(IPrincipalRoleMap(group)) return prms
def _do_save(self, data): group_role_changed = False prm = IPrincipalRoleMap(get_group_context(self.context)) if (data["group_role"] != self.context.group_role): if (prm.getSetting(self.context.group_role, self.context.principal_name) == Allow): group_role_changed = True unset_group_local_role(self.context) formlib.form.applyChanges(self.context, self.form_fields, data) if group_role_changed: set_group_local_role(self.context) notify(ObjectModifiedEvent(self.context))
def _query(self, **kw): principal = common.get_request_principal() roles = get_workspace_roles() group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] count = 0 reverse = True if (kw.get("sort_dir", "desc") == "desc") else False for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)).enable_eagerloads(False) #filter on title query = self.filter_title(query, domain_class, kw) #filter on status_date query = self.filter_status_date(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) results.extend(query.all()) for obj_role in ROLES_DIRECTLY_DEFINED_ON_OBJECTS: object_roles_domain_status = self.item_status_filter( kw, [obj_role]) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)).enable_eagerloads(False) #filter on title query = self.filter_title(query, domain_class, kw) #filter on status_date query = self.filter_status_date(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) for obj in query.all(): if obj in results: continue prm = IPrincipalRoleMap(obj) if (prm.getSetting(obj_role, principal.id) == Allow): results.append( contained(obj, self, self.string_key(obj))) results = [ item for item in results if checkPermission(view_permission(item), contained(item, self, self.string_key(item))) ] # Sort items if (kw.get("sort_on", None) and kw.get("sort_dir", None)): results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=reverse) count = len(results) if not (kw.get("filter_title", None) or kw.get("filter_type", None) or kw.get("filter_status", None) or kw.get("filter_status_date", None)): self.set_tab_count(principal.id, count) return (results, count)
def settingsForObject(ob): """Analysis tool to show all of the grants to a process """ result = [] while ob is not None: data = {} result.append((getattr(ob, '__name__', '(no name)'), data)) principalPermissions = IPrincipalPermissionMap(ob, None) if principalPermissions is not None: settings = principalPermissions.getPrincipalsAndPermissions() settings.sort() data['principalPermissions'] = [ {'principal': pr, 'permission': p, 'setting': s} for (p, pr, s) in settings] principalRoles = IPrincipalRoleMap(ob, None) if principalRoles is not None: settings = principalRoles.getPrincipalsAndRoles() data['principalRoles'] = [ {'principal': p, 'role': r, 'setting': s} for (r, p, s) in settings] rolePermissions = IRolePermissionMap(ob, None) if rolePermissions is not None: settings = rolePermissions.getRolesAndPermissions() data['rolePermissions'] = [ {'permission': p, 'role': r, 'setting': s} for (p, r, s) in settings] ob = getattr(ob, '__parent__', None) data = {} result.append(('global settings', data)) settings = principalPermissionManager.getPrincipalsAndPermissions() settings.sort() data['principalPermissions'] = [ {'principal': pr, 'permission': p, 'setting': s} for (p, pr, s) in settings] settings = principalRoleManager.getPrincipalsAndRoles() data['principalRoles'] = [ {'principal': p, 'role': r, 'setting': s} for (r, p, s) in settings] settings = rolePermissionManager.getRolesAndPermissions() data['rolePermissions'] = [ {'permission': p, 'role': r, 'setting': s} for (p, r, s) in settings] return result
def _query(self, **kw): principal = utils.get_principal() roles = get_workspace_roles() group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] count = 0 reverse = True if (kw.get("sort_dir", "desc") == "desc") else False for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)).enable_eagerloads(False) #filter on title query = self.filter_title(query, domain_class, kw) #filter on status_date query = self.filter_status_date(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) results.extend(query.all()) for obj_role in ROLES_DIRECTLY_DEFINED_ON_OBJECTS: object_roles_domain_status = self.item_status_filter( kw, [obj_role]) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)).enable_eagerloads(False) #filter on title query = self.filter_title(query, domain_class, kw) #filter on status_date query = self.filter_status_date(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) for obj in query.all(): if obj in results: continue prm = IPrincipalRoleMap(obj) if (prm.getSetting(obj_role, principal.id) == Allow): results.append( contained(obj, self, self.string_key(obj))) results = [item for item in results if checkPermission( view_permission(item), contained(item, self, self.string_key(item)))] # Sort items if (kw.get("sort_on", None) and kw.get("sort_dir", None)): results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=reverse) count = len(results) if not (kw.get("filter_title", None) or kw.get("filter_type", None) or kw.get("filter_status", None) or kw.get("filter_status_date", None) ): self.set_tab_count(principal.id, count) return (results, count)
def _query(self, **kw): principal = get_principal() roles = get_workspace_roles() group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] count = 0 first_page = not kw.get("start", 0) reverse = True if (kw.get("sort_dir", "desc") == "desc") else False for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status) ) #filter on title query = self.filter_query(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) # The first page of the results is loaded the most number of times # The limit on the query below optimises for when no filter has # been applied by limiting the number of results returned. if first_page: count = count + query.count() query = query.limit(kw.get("limit", 25)) results.extend(query.all()) object_roles_domain_status = self.item_status_filter(kw, OBJECT_ROLES) for domain_class, status in object_roles_domain_status.iteritems(): object_roles_results = [] query = session.query(domain_class).filter( domain_class.status.in_(status) ) #filter on title query = self.filter_query(query, domain_class, kw) # Order results query = self.order_query(query, domain_class, kw, reverse) for obj in query.all(): prm = IPrincipalRoleMap(obj) for obj_role in OBJECT_ROLES: if (prm.getSetting(obj_role, principal.id) == Allow and obj not in results): object_roles_results.append(obj) break if first_page: count = count + len(object_roles_results) results.extend(object_roles_results) # Sort items if (kw.get("sort_on", None) and kw.get("sort_dir", None)): results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=reverse) if not first_page: count = len(results) return (results, count)
def _query(self, **kw): principal = get_principal() roles = get_workspace_roles() group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] count = 0 for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter("""(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"].lower())) # The first page of the results is loaded the most number of times # The limit on the query below optimises for when no filter has # been applied by limiting the number of results returned. if (not kw.get("start", 0) and not kw.get("sort_on", None)): count = count + query.count() query = query.order_by(domain_class.status_date).limit( kw.get("limit", 25)) results.extend(query.all()) object_roles_domain_status = self.item_status_filter(kw, OBJECT_ROLES) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter("""(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"])) if (not kw.get("start", 0) and not kw.get("sort_on", None)): count = count + query.count() query = query.order_by(domain_class.status_date).limit( kw.get("limit", 25)) for obj in query.all(): prm = IPrincipalRoleMap(obj) for obj_role in OBJECT_ROLES: if (prm.getSetting(obj_role, principal.id) == Allow and obj not in results): results.append(obj) break # Sort items if (kw.get("sort_on", None) and kw.get("sort_dir", None)): rev = True if (kw.get("sort_dir") == "desc") else False results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=rev) if (kw.get("start", 0) and kw.get("sort_on", None)): count = len(results) return (results, count)
def publish_to_xml(context, type='', include=['event', 'versions']): """ Generates XML for object and saves it to the file. If object contains attachments - XML is saved in zip archive with all attached files. """ try: context = removeSecurityProxy(context) data = obj2dict( context, 1, parent=None, include=include, exclude=['file_data', 'image', 'logo_data', 'event_item']) if not type: type = context.type data['permissions'] = [] map = IPrincipalRoleMap(context) for x in list(map.getPrincipalsAndRoles()): data['permissions'].append({ 'role': x[0], 'user': x[1], 'permission': x[2].getName() }) files = [] path = os.path.join(setupStorageDirectory(), type) if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, context.__name__) files.append(file_path + '.xml') with open(file_path + '.xml', 'w') as file: file.write(serialize(data, name=type)) try: if len(context.attached_files) > 0: for attachment in context.attached_files: attachment_path = os.path.join(path, attachment.file_name) files.append(attachment_path) with open(os.path.join(path, attachment.file_name), 'wb') as file: file.write(attachment.file_data) zip = ZipFile(file_path + '.zip', 'w') for file in files: zip.write(file, os.path.split(file)[-1]) os.remove(file) zip.close() except AttributeError: pass except: traceback.print_exception(*sys.exc_info())
def get_pids_with_role_on_context(context, role_id): """Get the principal_ids (via the PrincipalRoleMap) who have the role on the context, if any. """ return [ pid for (pid, setting) in IPrincipalRoleMap(context).getPrincipalsForRole(role_id) if setting ]
def assign_question_minister_role(context): assert interfaces.IQuestion.providedBy(context), \ "Not a Question: %s" % (context) if context.ministry is not None: ministry_login_id = context.ministry.group_principal_id if ministry_login_id: IPrincipalRoleMap(context).assignRoleToPrincipal( "bungeni.Minister", ministry_login_id)
def assign_role(role_id, principal_id, context): """Add or activate implied role on this context, for implied principal. !+check if already defined and active, inactive? !+PrincipalRoleMapDynamic(mr, may-2012) infer role from context data """ log.debug("Assigning role [%s] to principal [%s] on [%s]", role_id, principal_id, context) # throws IntegrityError when principal_id is None IPrincipalRoleMap(context).assignRoleToPrincipal(role_id, principal_id)
def cached_principal_roles(self, parent, principal): cache = self.cache(parent) try: cache_principal_roles = cache.principal_roles except AttributeError: cache_principal_roles = cache.principal_roles = {} try: return cache_principal_roles[principal] except KeyError: pass if parent is None: roles = dict( [(role, zopepolicy.SettingAsBoolean[setting]) for (role, setting) in zopepolicy.globalRolesForPrincipal(principal)]) roles['zope.Anonymous'] = True # Everybody has Anonymous cache_principal_roles[principal] = roles return roles roles = self.cached_principal_roles( removeSecurityProxy(getattr(parent, '__parent__', None)), principal) prinrole = IPrincipalRoleMap(parent, None) if prinrole: roles = roles.copy() for role, setting in prinrole.getRolesForPrincipal(principal): roles[role] = zopepolicy.SettingAsBoolean[setting] # The lines below include the group that a document has been assigned # to into the lookup hierarchy. group_assignments = getattr(parent, "sa_group_assignments", []) for group_assignment in group_assignments: group = group_assignment.principal #!+GROUP_ASSIGNMENT.GROUP assert isinstance(group, domain.Group), group assigned_group_prinrole = IPrincipalRoleMap(group, None) if assigned_group_prinrole: roles = roles.copy() role_settings = assigned_group_prinrole.getRolesForPrincipal( principal) for role, setting in role_settings: roles[role] = zopepolicy.SettingAsBoolean[setting] cache_principal_roles[principal] = roles return roles
def extend_results_for_roles(roles): domain_status = self.item_status_filter(kw, roles) OBJECT_ROLES = [ role for role in roles if role in ROLES_DIRECTLY_DEFINED_ON_OBJECTS ] for domain_class, status in domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)).enable_eagerloads(False) query = self.filter_group(query, domain_class, kw) query = self.filter_title(query, domain_class, kw) query = self.filter_status_date(query, domain_class, kw) query = self.order_query(query, domain_class, kw, reverse) for obj in query.all(): if obj in results: continue if OBJECT_ROLES: prm = IPrincipalRoleMap(obj) if not prm.getSetting(obj_role, principal_id) == Allow: continue results.append(contained(obj, self, self.string_key(obj)))
def get_principal_ids(document, roles): principal_ids = set() document_prm = IPrincipalRoleMap(document) group_prms = get_group_prms(document) for role in roles: if role in ROLES_DIRECTLY_DEFINED_ON_OBJECTS: principals = document_prm.getPrincipalsForRole(role) for principal in principals: principal_ids.add(principal[0]) else: for group_prm in group_prms: principals = group_prm.getPrincipalsForRole(role) for principal in principals: principal_id = principal[0] if principal_id.startswith("group"): group_mbr_ids = get_group_member_ids(principal_id) for group_mbr in group_mbr_ids: principal_ids.add(group_mbr) return principal_ids
def _query(self, **kw): principal = get_principal() roles = get_workspace_roles(principal) group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status) ) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter( """(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"].lower()) ) results.extend(query.all()) object_roles_domain_status = self.item_status_filter(kw, OBJECT_ROLES) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter( """(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"]) ) for obj in query.all(): prm = IPrincipalRoleMap(obj) for obj_role in OBJECT_ROLES: if (prm.getSetting(obj_role, principal.id) == Allow and obj not in results ): results.append(obj) break # Sort items if kw.get("sort_on", None): if kw.get("sort_dir", None): rev = True if (kw.get("sort_dir") == "desc") else False results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=rev) return results
def getAllRoles(self): hfr = IPrincipalRoleMap(self.homefolder) masteruser = False ret = [] for rolesetting in hfr.getRolesForPrincipal(self.principal.id): role, setting = rolesetting if 'uvc.Editor' == role and setting is Allow: masteruser = True ret.append('ENMS') for name, productfolder in self.homefolder.items(): if not name.startswith('__'): if masteruser: ret.append(name) else: prm = IPrincipalRoleMap(productfolder) for rolesetting in prm.getRolesForPrincipal(self.principal.id): role, setting = rolesetting if 'uvc.Editor' == role and setting is Allow: ret.append(name) return ret
def setup_roles(self): if self.document_submitted(): make_owner_signatory(self.context) for signatory in self.signatories: login_id = signatory.owner.login IPrincipalRoleMap(self.context).assignRoleToPrincipal( SIGNATORY_ROLE, login_id) IPrincipalRoleMap(signatory).assignRoleToPrincipal( OWNER_ROLE, login_id) elif self.document_is_draft(): for signatory in self.signatories: IPrincipalRoleMap(self.context).unsetRoleForPrincipal( SIGNATORY_ROLE, signatory.owner.login) elif self.expire_signatures(): for signatory in self.signatories: wfc = IWorkflowController(signatory) if (wfc.state_controller.get_status() in SIGNATORIES_REJECT_STATES): IPrincipalRoleMap(self.context).unsetRoleForPrincipal( SIGNATORY_ROLE, signatory.owner.login)
async def sharing_get(context, request): roleperm = IRolePermissionMap(context) prinperm = IPrincipalPermissionMap(context) prinrole = IPrincipalRoleMap(context) result = {'local': {}, 'inherit': []} result['local']['role_permission'] = roleperm._byrow result['local']['principal_permission'] = prinperm._byrow result['local']['principal_role'] = prinrole._byrow for obj in iter_parents(context): roleperm = IRolePermissionMap(obj) prinperm = IPrincipalPermissionMap(obj) prinrole = IPrincipalRoleMap(obj) result['inherit'].append({ '@id': IAbsoluteURL(obj, request)(), 'role_permission': roleperm._byrow, 'principal_permission': prinperm._byrow, 'principal_role': prinrole._byrow, }) await notify(ObjectPermissionsViewEvent(context)) return result
def getUsers(self): users = {} settings = IPrincipalRoleMap(self.context).getPrincipalsAndRoles() for role, userid, access in settings: if access is Allow: if userid in users: users[userid].add(role) else: users[userid] = set((role,)) users['zope.Authenticated'] = set() users['zope.Everybody'] = set() return users
def publish_to_xml(context, type='', include=['event','versions']): """ Generates XML for object and saves it to the file. If object contains attachments - XML is saved in zip archive with all attached files. """ try: context = removeSecurityProxy(context) data = obj2dict(context,1,parent=None,include=include,exclude=['file_data', 'image', 'logo_data','event_item']) if not type: type = context.type data['permissions']= [] map = IPrincipalRoleMap(context) for x in list(map.getPrincipalsAndRoles()): data['permissions'].append({'role':x[0], 'user':x[1], 'permission':x[2].getName()}) files = [] path = os.path.join(setupStorageDirectory(), type) if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path,context.__name__) files.append(file_path+'.xml') with open(file_path+'.xml','w') as file: file.write(serialize(data, name=type)) try: if len(context.attached_files) > 0: for attachment in context.attached_files: attachment_path = os.path.join(path, attachment.file_name) files.append(attachment_path) with open(os.path.join(path, attachment.file_name), 'wb') as file: file.write(attachment.file_data) zip = ZipFile(file_path+'.zip', 'w') for file in files: zip.write(file, os.path.split(file)[-1]) os.remove(file) zip.close() except AttributeError: pass except: traceback.print_exception(*sys.exc_info())
def get_prm_owner_principal_id(context): """Get the principal_id, if any, of the bungeni.Owner for context. Raise ValueError if multiple, return None if none. """ principal_ids = [ pid for (pid, setting) in IPrincipalRoleMap( context).getPrincipalsForRole("bungeni.Owner") if setting ] len_pids = len(principal_ids) if len_pids > 1: # multiple Owner roles, force exception raise ValueError("Ambiguous, multiple Owner roles assigned.") elif len_pids == 1: return principal_ids[0]
def _query(self, **kw): principal = get_principal() roles = get_workspace_roles(principal) group_roles_domain_status = self.item_status_filter(kw, roles) session = Session() results = [] for domain_class, status in group_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter("""(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"].lower())) results.extend(query.all()) object_roles_domain_status = self.item_status_filter(kw, OBJECT_ROLES) for domain_class, status in object_roles_domain_status.iteritems(): query = session.query(domain_class).filter( domain_class.status.in_(status)) if kw.get("filter_short_name", None): column = self.title_column(domain_class) query = query.filter("""(lower(%s) LIKE '%%%s%%')""" % (column, kw["filter_short_name"])) for obj in query.all(): prm = IPrincipalRoleMap(obj) for obj_role in OBJECT_ROLES: if (prm.getSetting(obj_role, principal.id) == Allow and obj not in results): results.append(obj) break # Sort items if kw.get("sort_on", None): if kw.get("sort_dir", None): rev = True if (kw.get("sort_dir") == "desc") else False results.sort(key=lambda x: getattr(x, str(kw.get("sort_on"))), reverse=rev) return results
def cached_principal_roles(self, parent, principal): cache = self.cache(parent) try: cache_principal_roles = cache.principal_roles except AttributeError: cache_principal_roles = cache.principal_roles = {} try: return cache_principal_roles[principal] except KeyError: pass if parent is None: roles = dict([(role, SettingAsBoolean[setting]) for (role, setting) in globalRolesForPrincipal(principal)]) roles['zope.Anonymous'] = True # Everybody has Anonymous cache_principal_roles[principal] = roles return roles if getattr(parent, 'inherit_permissions', False): roles = self.cached_principal_roles( removeSecurityProxy(getattr(parent, '__parent__', None)), principal) else: roles = dict([(role, SettingAsBoolean[setting]) for (role, setting) in globalRolesForPrincipal(principal)]) roles['zope.Anonymous'] = True # Everybody has Anonymous prinrole = IPrincipalRoleMap(parent, None) if prinrole: for role, setting in prinrole.getRolesForPrincipal(principal): roles[role] = SettingAsBoolean[setting] cache_principal_roles[principal] = roles return roles
def get_members(context, role_id): members = [] auth = getUtility(IAuthentication) for ob in LocationIterator(context): for x in IPrincipalRoleMap(ob).getPrincipalsForRole(role_id): if x[1] == Allow: try: group = auth.getPrincipal(x[0]) for pid in group.getMembers(): if pid not in members: try: members.append(auth.getPrincipal(pid)) except PrincipalLookupError: pass # TODO: remove member from group? except PrincipalLookupError: IPrincipalRoleManager(ob).removeRoleFromPrincipal( x[0], role_id) return members
def cached_principal_roles(self, parent, principal): cache = self.cache(parent) try: cache_principal_roles = cache.principal_roles except AttributeError: cache_principal_roles = cache.principal_roles = {} try: return cache_principal_roles[principal] except KeyError: pass if parent is None: roles = dict([ (role, zopepolicy.SettingAsBoolean[setting]) for (role, setting) in zopepolicy.globalRolesForPrincipal(principal) ]) roles['zope.Anonymous'] = True # Everybody has Anonymous cache_principal_roles[principal] = roles return roles roles = self.cached_principal_roles( removeSecurityProxy(getattr(parent, '__parent__', None)), principal) prinrole = IPrincipalRoleMap(parent, None) if prinrole: roles = roles.copy() for role, setting in prinrole.getRolesForPrincipal(principal): roles[role] = zopepolicy.SettingAsBoolean[setting] # The lines below include the group that a document has been assigned # to into the lookup hierarchy. group_assignments = getattr(parent, "sa_group_assignments", []) for group_assignment in group_assignments: group = group_assignment.principal #!+GROUP_ASSIGNMENT.GROUP assert isinstance(group, domain.Group), group assigned_group_prinrole = IPrincipalRoleMap(group, None) if assigned_group_prinrole: roles = roles.copy() role_settings = assigned_group_prinrole.getRolesForPrincipal( principal) for role, setting in role_settings: roles[role] = zopepolicy.SettingAsBoolean[setting] cache_principal_roles[principal] = roles return roles
def getAllRoles(self): ret = [] hfr = IPrincipalRoleMap(self.homefolder, None) if hfr is None: return ret masteruser = False for rolesetting in hfr.getRolesForPrincipal(self.principal.id): role, setting = rolesetting if 'uvc.Editor' == role and setting is Allow: masteruser = True ret.append('ENMS') for name, productfolder in self.homefolder.items(): if not name.startswith('__'): if masteruser: ret.append(name) else: prm = IPrincipalRoleMap(productfolder) for rolesetting in prm.getRolesForPrincipal( self.principal.id): role, setting = rolesetting if 'uvc.Editor' == role and setting is Allow: ret.append(name) return ret
class UserAssignmentView(forms.common.BaseForm): """View for user assignments. Allows users with adequate permissions to edit the assignments """ form_fields = [] render = ViewPageTemplateFile("templates/assignment.pt") def __init__(self, context, request): self._assignable_roles = [] self.principal = utils.common.get_request_principal() self.context_roles = common.get_context_roles( context, self.principal) self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) super(UserAssignmentView, self).__init__(context, request) def __call__(self): self.update() return self.render() def get_object_type_info(self): return capi.get_type_info(self.context.__class__) def get_config_roles(self, role_type): ti = self.get_object_type_info() workflow = ti.workflow if workflow.has_feature("user_assignment"): feature = None for f in workflow.features: if f.name == "user_assignment": feature = f if feature: if role_type == "assigner": return capi.schema.qualified_roles(feature.params["assigner_roles"]) elif role_type == "assignable": return capi.schema.qualified_roles(feature.params["assignable_roles"]) return [] def assignable_roles(self): """Returns a list of role ids that this user can assign to """ if self._assignable_roles: return self._assignable_roles # the assigner roles that this user has assigner_roles = [] # all the assigner roles that are in the workflow config config_assigner_roles = self.get_config_roles("assigner") for c_a_role in config_assigner_roles: role = getUtility(IRole, c_a_role) if role.id in self.context_roles: assigner_roles.append(role.id) # the assignable roles that this user can assign to assignable_roles = [] # all the assignable roles that are in the workflow config config_assignable_roles = self.get_config_roles("assignable") # Only assign to roles that have the same parent or are children # of assigner roles that this user has for assigner_role in assigner_roles: assigner_role_annt = ISubRoleAnnotations( getUtility(IRole, assigner_role)) if assigner_role_annt.is_sub_role: for c_assignable_role in config_assignable_roles: c_assignable_role_annt = ISubRoleAnnotations( getUtility(IRole, c_assignable_role)) if (c_assignable_role_annt.parent == assigner_role_annt.parent): assignable_roles.append(c_assignable_role) else: for c_assignable_role in config_assignable_roles: if (c_assignable_role in assigner_role_annt.sub_roles): assignable_roles.append(c_assignable_role) self._assignable_roles = assignable_roles return self._assignable_roles def can_edit(self, action=None): return checkPermission("bungeni.user_assignment.Edit", self.context) @property def columns(self): return [ column.GetterColumn( title=_("user name"), getter=lambda i, f: i.get("title") ), column.GetterColumn( title=_("assigned"), getter=lambda i, f: i, cell_formatter=lambda g, i, f: \ '<input type="checkbox" name="%s" %s %s/>' % ( i["name"], i["is_assigned"] and ' checked="checked"' or "", not i["editable"] and ' disabled="disabled"' or "") ) ] @property def checkbox_prefix(self): return "assignment_users" def make_id(self, role_id, user_login_id): return ".".join( (self.checkbox_prefix, role_id, user_login_id)) def user_is_assigned(self, user_login, role_id): if self.prm.getSetting(role_id, user_login) == Allow: return True return False def role_listing(self, role_id, editable): listing = [] users = common.get_users(role_id) if not users: return _("No users available for this role.") for user in users: data = {} data["title"] = IDCDescriptiveProperties(user).title data["name"] = self.make_id(user.login, role_id) data["is_assigned"] = self.user_is_assigned(user.login, role_id) data["editable"] = editable listing.append(data) formatter = TableFormatter( self.context, self.request, listing, prefix="assignment", columns=self.columns) formatter.updateBatching() return formatter() def update(self): self.tables = [] assignable_roles = self.assignable_roles() for role_id in assignable_roles: if role_id in assignable_roles: editable = True else: editable = False self.tables.append( {"title": getUtility(IRole, role_id).title, "table": self.role_listing(role_id, editable)}) forms.common.BaseForm.update(self) def get_selected(self): selected = [ (k[len(self.checkbox_prefix) + 1:].split(".")[0].decode("base64"), k[len(self.checkbox_prefix) + 1:].split(".")[1].decode("base64")) for k in self.request.form.keys() if k.startswith(self.checkbox_prefix) and self.request.form.get(k) ] return selected def process_assignment(self): for role_id in self.assignable_roles(): for user in common.get_users(role_id): key = self.make_id(user.login, role_id) if key in self.request.form.keys(): self.prm.assignRoleToPrincipal(role_id, user.login) else: self.prm.unsetRoleForPrincipal(role_id, user.login) @formlib.form.action(label=_("Save"), name="save", condition=can_edit) def handle_save(self, action, data): self.process_assignment() next_url = url.absoluteURL(self.context, self.request) self.request.response.redirect(next_url) @formlib.form.action(label=_("Cancel"), name="", condition=can_edit) def handle_cancel(self, action, data): next_url = url.absoluteURL(self.context, self.request) self.request.response.redirect(next_url)
def unset_role(role_id, principal_id, context): log.debug("Unsetting role [%s] for principal [%s] on [%s]", role_id, principal_id, context) IPrincipalRoleMap(context).unsetRoleForPrincipal(role_id, principal_id)
class GenerateDebateRecordTakes(BungeniBrowserView, ui.BaseForm): """View to generate takes """ form_fields = [] template = NamedTemplate("alchemist.subform") def __init__(self, context, request): if IDebateTakeContainer.providedBy(context): self.context = removeSecurityProxy(context).__parent__ else: self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) self.request = request #super(GenerateDebateRecordTakes, self).__init__(context, request) def get_take_duration(self): return component.getUtility(IDebateRecordConfig).get_take_duration() def get_transcriber_role(self): return component.getUtility(IDebateRecordConfig).get_transcriber_role() def get_transcribers(self): transcribers = [] transcriber_role = self.get_transcriber_role() users = common.get_local_users_for_subrole(transcriber_role) for user in users: if self.user_is_assigned(user.login, transcriber_role): transcribers.append(user) return transcribers def user_is_assigned(self, user_login, role_id): if self.prm.getSetting(role_id, user_login) == Allow: return True return False def get_take_name(self, take_count): take_name_prefix = "" b_take_count = take_count while (take_count / 26): take_count = take_count / 26 take_name_prefix = take_name_prefix + chr(64 + take_count) return take_name_prefix + chr(65 + (b_take_count % 26)) def has_no_takes(self, action=None): return False if len(self.context.debate_takes) > 0 else True @formlib.form.action(label=_("Generate takes"), name="generate", condition=has_no_takes) def handle_generate_takes(self, action, data): transcribers = self.get_transcribers() next_url = url.absoluteURL(self.context, self.request) if not transcribers: return self.request.response.redirect(next_url + "/takes") sitting = self.context.sitting take_time_delta = datetime.timedelta(seconds=self.get_take_duration()) current_end_time = sitting.start_date current_start_time = sitting.start_date take_count = 0 session = Session() while current_end_time < sitting.end_date: take = domain.DebateTake() take.debate_record_id = self.context.debate_record_id take.start_date = current_start_time if ((current_end_time + take_time_delta) > sitting.end_date): current_end_time = sitting.end_date else: current_end_time = current_end_time + take_time_delta current_start_time = current_end_time + datetime.timedelta( seconds=1) take.end_date = current_end_time take.transcriber_id = transcribers[ take_count % len(transcribers)].user_id take.debate_take_name = self.get_take_name(take_count) take_count = take_count + 1 session.add(take) session.flush() return self.request.response.redirect(next_url + "/takes")
def __init__(self, context, request): self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) super(DebateRecordTakes, self).__init__(context, request)
class DebateRecordTakes(BungeniBrowserView, forms.common.BaseForm): """View to generate takes """ form_fields = [] render = ViewPageTemplateFile("templates/debate-takes.pt") def __init__(self, context, request): self.context = removeSecurityProxy(context) self.prm = IPrincipalRoleMap(self.context) super(DebateRecordTakes, self).__init__(context, request) def __call__(self): self.update() self.listing = self.formatted_listing() return self.render() def columns(self): date_formatter = date.getLocaleFormatter(common.get_request(), "dateTime", "medium") listing_columns = [ column.GetterColumn( title=_("Take start time"), getter=lambda i,f: date_formatter.format(i.start_date) ), column.GetterColumn( title=_("Take end time"), getter=lambda i,f: date_formatter.format(i.end_date) ), column.GetterColumn( title=_("Take name"), getter=lambda i,f: i.debate_take_name ), column.GetterColumn( title=_("Take transcriber"), getter=lambda i,f: IDCDescriptiveProperties(i.user).title ), ] return listing_columns def formatted_listing(self): formatter = TableFormatter(self.context, self.request, self.context.debate_takes, columns=self.columns() ) formatter.updateBatching() return formatter() def get_take_duration(self): return component.getUtility(IDebateRecordConfig).get_take_duration() def get_transcriber_role(self): return component.getUtility(IDebateRecordConfig).get_transcriber_role() def get_transcribers(self): transcribers = [] transcriber_role = self.get_transcriber_role() users = common.get_users(transcriber_role) for user in users: if self.user_is_assigned(user.login, transcriber_role): transcribers.append(user) return transcribers def user_is_assigned(self, user_login, role_id): if self.prm.getSetting(role_id, user_login) == Allow: return True return False def get_take_name(self, take_count): take_name_prefix = "" b_take_count = take_count while (take_count / 26): take_count = take_count / 26 take_name_prefix = take_name_prefix + chr(64+take_count) return take_name_prefix + chr(65+(b_take_count%26)) def has_no_takes(self, action=None): return False if len(self.context.debate_takes) > 0 else True @formlib.form.action(label=_("Generate takes"), name="generate", condition=has_no_takes) def handle_generate_takes(self, action, data): transcribers = self.get_transcribers() sitting = self.context.sitting take_time_delta = datetime.timedelta(seconds=self.get_take_duration()) current_end_time = sitting.start_date current_start_time = sitting.start_date take_count = 0 session = Session() while current_end_time < sitting.end_date: take = domain.DebateTake() take.debate_record_id = self.context.debate_record_id take.start_date = current_start_time if ((current_end_time + take_time_delta) > sitting.end_date): current_end_time = sitting.end_date else: current_end_time = current_end_time + take_time_delta current_start_time = current_end_time + datetime.timedelta( seconds=1) take.end_date = current_end_time take.transcriber_id = transcribers[ take_count % len(transcribers)].user_id take.debate_take_name = self.get_take_name(take_count) take_count = take_count+1 session.add(take) session.flush() next_url = url.absoluteURL(self, self.request) self.request.response.redirect(next_url)
def group_membership_role_added(group_membership_role, event): if group_membership_role.is_global: prm = IPrincipalRoleMap(get_group_context(group_membership_role.member.group)) prm.assignRoleToPrincipal(group_membership_role.role_id, group_membership_role.member.user.login)
def group_membership_role_deleted(group_membership_role, event): if group_membership_role.is_global: prm = IPrincipalRoleMap(get_group_context(group_membership_role.member.group)) prm.unsetRoleForPrincipal(group_membership_role.role_id, group_membership_role.member.user.login)
def title_created(title, event): prm = IPrincipalRoleMap(get_group_context(title.title_type.group)) prm.assignRoleToPrincipal(title.title_type.role_id, title.member.user.login)
def title_deleted(membership, event): prm = IPrincipalRoleMap(get_group_context(title.title_type.group)) prm.unsetRoleForPrincipal(title.title_type.role_id, title.member.user.login)
def roles(self): prmap = IPrincipalRoleMap(self.context) return [ids for ids, setting in prmap.getRolesForPrincipal(self.principal_id)]