def issue_transition_handler(ob, e): if e.transition.transition_id in UPDATE_RESPONSIBILITY: clean_roles(ob, "dynamic_tacklets.project.DocumentResponsible") prinrole = IPrincipalRoleManager(ob) principal_id = IResponsibility(ob).responsible prinrole.assignRoleToPrincipal("dynamic_tacklets.project.DocumentResponsible", principal_id)
def addUser(self, username, email, password, real_name, role): if username not in self.user_folder: user = Account(username, email, password, real_name, role) self.user_folder[username] = user role_manager = IPrincipalRoleManager(grok.getSite()) print role, username role_manager.assignRoleToPrincipal(role, username)
def setup_site_manager(self, context): context.setSiteManager(LocalSiteManager(context)) sm = context.getSiteManager() pau = PluggableAuthentication(prefix='2f.pau.') notify(ObjectCreatedEvent(pau)) sm[u'authentication'] = pau context['PluggableAuthentication'] = pau sm.registerUtility(pau, IAuthentication) annotation_utility = PrincipalAnnotationUtility() sm.registerUtility(annotation_utility, IPrincipalAnnotationUtility) session_data = PersistentSessionDataContainer() sm.registerUtility(session_data, ISessionDataContainer) client_id_manager = CookieClientIdManager() notify(ObjectCreatedEvent(client_id_manager)) sm[u'CookieClientIdManager'] = client_id_manager sm.registerUtility(client_id_manager, ICookieClientIdManager) principals = PrincipalFolder(prefix='users') notify(ObjectCreatedEvent(principals)) pau[u'users'] = principals pau.authenticatorPlugins += (u"users", ) notify(ObjectModifiedEvent(pau)) pau.credentialsPlugins = (u'TwoFactor Session Credentials',) admin1 = InternalPrincipal('admin1', 'admin1', "Admin 1", passwordManagerName="Plain Text") principals['admin1'] = admin1 role_manager = IPrincipalRoleManager(context) login_name = principals.getIdByLogin(admin1.login) pid = unicode('2f.pau.' + login_name) role_manager.assignRoleToPrincipal('zope.Manager', pid)
def addUser(self, username, password, real_name): user_folder = grok.getSite()['users'] if username not in user_folder: user = Account(username, password, real_name) user_folder[username] = user role_manager = IPrincipalRoleManager(grok.getSite()) role_manager.assignRoleToPrincipal('merlot.Manager', username)
def handle_signin(self, **data): """signin button and signin action """ # create the people people = People() self.applyData(people, **data) # check the login is not taken if people.login in self.peoplelist: msg = _(u'This username already exists: %s') SessionMessageSource().send( translate(msg, context=self.request) % people.login) return self.redirect('signin') # generate a weak but nice password password = u''.join([ choice([ 'z', 'r', 't', 'p', 'q', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'w', 'x', 'c', 'v', 'b', 'n' ]) + choice(['a', 'e', 'i', 'o', 'u', 'y']) for i in range(4) ]) people.password = password # send an email with the password site = grok.getSite() email = _(u'''Content-Type: text/plain; charset=UTF-8 Subject: your account for %s Dear %s %s, Thanks for your account! You can connect to %s with the following informations: %s login : %s password : %s''') url = absoluteURL(site, self.request) if ('HTTP_X_FORWARDED_SCHEME' in self.request and 'HTTP_X_FORWARDED_SERVER' in self.request): url = (self.request['HTTP_X_FORWARDED_SCHEME'] + '://' + self.request['HTTP_X_FORWARDED_SERVER']) email = translate(email, context=self.request) % ( site.name, people.firstname, people.lastname, site.name, url, people.login, password) mailer = getUtility(IMailDelivery, 'afpy.barcamp') if 'nomail' not in self.request: mailer.send('*****@*****.**', people.email.encode('utf-8'), email.encode('utf-8')) # add the user self.peoplelist[people.login] = people # grant him the Member role prm = IPrincipalRoleManager(grok.getSite()) prm.assignRoleToPrincipal('afpy.barcamp.Member', people.login) self.redirect('confirmation')
def applyPermissionsForExistentCoUsers(factory): site = grok.getSite() hfm = IHomeFolderManager(site) principal = factory.object master_id = IMasterUser(principal).id if hfm.get(master_id) is None: hfm.create(IMasterUser(principal).id) homefolder = principal.homefolder #IHomeFolder(principal) if homefolder is None: return um = getUtility(IUserManagement) user = um.getUser(principal.id) if not user: return rollen = user['rollen'] if user['az'] != '00': pid = "%s-%s" % (user['mnr'], user['az']) else: pid = user['mnr'] if homefolder.__name__ != pid: for pf in homefolder.keys(): if pf in rollen: prm = IPrincipalRoleManager(homefolder.get(pf)) if prm.getSetting('uvc.Editor', pid).getName() == 'Unset': prm.assignRoleToPrincipal('uvc.Editor', pid) uvcsite.log('Give uvc.Editor to %s in folder %s' % (pid, pf))
class PrincipalRoles(grok.Adapter): """Grant a role to a principal. """ grok.context(IPrincipal) grok.implements(IPrincipalRoles) def __init__(self, context): site = getSite() self.userid = context.id self.manager = IPrincipalRoleManager(site) @apply def roles(): """Writable property for roles. """ def get(self): setting = self.manager.getRolesForPrincipal(self.userid) return [role[0] for role in setting if role[1] is Allow] def set(self, roles): # removing undefined roles setting = self.manager.getRolesForPrincipal(self.userid) for role in setting: if role[0] not in roles and role[1] is Allow: self.manager.unsetRoleForPrincipal(role[0], self.userid) # setting new roles for role in roles: self.manager.assignRoleToPrincipal(role, self.userid) return property(get, set)
def applyViewContentForCoUsers(factory): principal = factory.object homefolder = None #if IUnauthenticatedPrincipal.providedBy(principal): # homefolder = principal.homefolder #else: # # Workaround, um weiter arbeiten zu können - CK muss noch fixen # #try: # # homefolder = IHomeFolder(principal) # #except TypeError: # # return # homefolder = IHomeFolder(principal) homefolder = principal.homefolder if not homefolder: return if homefolder.__name__ != principal.id: hprm = IPrincipalRoleManager(homefolder) if hprm.getSetting('uvc.HomeFolderUser', principal.id).getName() in ('Deny', 'Unset'): hprm.assignRoleToPrincipal('uvc.HomeFolderUser', principal.id) uvcsite.log( 'applying Role uvc.HomeFolderUser for USER %s in HOMEFOLDER %s' % (principal.id, homefolder.__name__))
def createPAU(event): """ Create a pau (pluggable authentication utility, a signup principal folder in it and a manger user (!).""" sm = event.object.getSiteManager() sm['default']['pau'] = pau = PluggableAuthentication() pau.prefix = 'pau.' pau['signup_principal_folder'] = folder = SignupPrincipalFolder() pau.authenticatorPlugins = [folder.__name__] folder.prefix = u"users." folder.signup_roles = [u'quotationtool.Member'] principal_id = folder.signUp('admin', 'Op3n', 'Quotationtool Manager') role_manager = IPrincipalRoleManager(event.object) role_manager = removeSecurityProxy(role_manager) role_manager.assignRoleToPrincipal('quotationtool.Manager', principal_id) pau['SessionCredentialsPlugin'] = session_creds = SessionCredentialsPlugin() pau.credentialsPlugins = [session_creds.__name__] session_creds.loginpagename = u"loginForm.html" loginfield = u"login" passwordfield = u"password" sm.registerUtility(pau, IAuthentication)
def update(self, **data): cn = '%s-%s' % (self.mnr, data.get('az')) self.um.updUser(**data) for role in self.__parent__.values(): principal_roles = IPrincipalRoleManager(role) principal_roles.removeRoleFromPrincipal('uvc.Editor', cn) for role in data.get('rollen'): principal_roles = IPrincipalRoleManager(self.__parent__[role]) principal_roles.assignRoleToPrincipal('uvc.Editor', cn)
def applyViewContentForCoUsers(factory): principal = factory.object homefolder = IHomeFolder(principal).homeFolder if not homefolder: return if homefolder.__name__ != principal.id: hprm = IPrincipalRoleManager(homefolder) if hprm.getSetting('uvc.HomeFolderUser', principal.id).getName() in ('Deny', 'Unset'): hprm.assignRoleToPrincipal('uvc.HomeFolderUser', principal.id) log('applying Role uvc.HomeFolderUser for USER %s in HOMEFOLDER %s' % (principal.id, homefolder.__name__))
def rolesFromAccount(self): ''' Populate the managed roles for this principal from self.roles ''' roleMgr = IPrincipalRoleManager(grok.getSite()) if self.login == 'admin': self.roles.add('gfn.Administrator') for rid, _setting in roleMgr.getRolesForPrincipal('gfn.'+self.login): roleMgr.unsetRoleForPrincipal(rid, 'gfn.'+self.login) for role in self.roles: roleMgr.assignRoleToPrincipal(role, 'gfn.'+self.login)
def setup_local(e): sm = e.manager site = sm.__parent__ # root folder intids = IntIds() sm[u'intids'] = intids sm.registerUtility(intids, IIntIds) catalog = Catalog() sm[u'catalog'] = catalog sm.registerUtility(catalog, ICatalog) catalog[u'fulltext'] = TextIndex(interface=ISearchableText, field_name='getSearchableText', field_callable=True) auth = PluggableAuthentication() sm[u'authentication'] = auth sm.registerUtility(auth, IAuthentication) pfolder = principalfolder.PrincipalFolder(prefix='principal.') auth[u'principalfolder'] = pfolder gfolder = groupfolder.GroupFolder(prefix='group.') auth[u'groupfolder'] = gfolder auth.credentialsPlugins += (u'Session Credentials',) auth.authenticatorPlugins += (u'principalfolder', u'groupfolder') pran = PrincipalAnnotationUtility() sm[u'principalannotation'] = pran sm.registerUtility(pran, IPrincipalAnnotationUtility) pwdreset = PasswordResetUtility() sm[u'passwordreset'] = pwdreset sm.registerUtility(pwdreset, IPasswordResetUtility) # default bootstrap admin login = u"manager" password = "******" pfolder[login] = principalfolder.InternalPrincipal(login, password, login, u"", "SSHA") principal_id = pfolder.prefix + login prinrole = IPrincipalRoleManager(site) prinrole.assignRoleToPrincipal('tackle.SystemManager', principal_id) # all authenticated users are guests by default prinrole.assignRoleToPrincipal('tackle.Guest', 'zope.Authenticated') # site title dc = IZopeDublinCore(site) dc.title = u"Tackle" # custom local setup notify(NewLocalSite(sm))
def applyViewContentForCoUsers(factory): principal = factory.object homefolder = IHomeFolder(principal).homeFolder if not homefolder: return if homefolder.__name__ != principal.id: hprm = IPrincipalRoleManager(homefolder) setting = hprm.getSetting('uvc.HomeFolderUser', principal.id).getName() if setting in ('Deny', 'Unset'): hprm.assignRoleToPrincipal('uvc.HomeFolderUser', principal.id) log('applying Role uvc.HomeFolderUser for USER %s in HOMEFOLDER %s' % (principal.id, homefolder.__name__))
def create(self, data): description = CategorizableItemDescription() form.applyChanges(self, description, data) # Grant the current user the Edit permission by assigning him # the quotationtool.Creator role, but only locally in the # context of the newly created object. manager = IPrincipalRoleManager(description) manager.assignRoleToPrincipal('quotationtool.Creator', self.request.principal.id) return description
def agregarUsuario(self, usuario, password, confirm_password, nombre_real, rol, seccion): if usuario not in self.contenedor_cuentas: user = Cuenta(usuario, password, nombre_real, rol, seccion) self.contenedor_cuentas[usuario] = user role_manager = IPrincipalRoleManager(grok.getSite()) if rol == u'empleado': role_manager.assignRoleToPrincipal('ct.empleadorol', usuario) if rol == u'administrador': role_manager.assignRoleToPrincipal('ct.adminrol', usuario) else: return u"El nombre de usuario ya existe"
def handle_add(self): data, errors = self.extractData() if errors: self.flash(u'Es ist ein Fehler aufgetreten', 'warning') return changes = apply_data_event(self.fields, self.context, data) role_manager = IPrincipalRoleManager(grok.getSite()) for role_id, setting in role_manager.getRolesForPrincipal(data['login']): role_manager.removeRoleFromPrincipal(role_id, data['login']) role_manager.assignRoleToPrincipal(data['role'], data['login']) print role_manager.getRolesForPrincipal(data['login']) self.redirect(self.url(grok.getSite(), '/benutzer'))
def create(self, data): category_set = CategorySet() form.applyChanges(self, category_set, data) # Grant the current user the Edit permission by assigning him # the quotationtool.Creator role, but only locally in the # context of the newly created object. manager = IPrincipalRoleManager(category_set) manager.assignRoleToPrincipal( 'quotationtool.Creator', self.request.principal.id) return category_set
def install(self): # Creating and registering a local registry self['_registry'] = registry = Registry() # Set default plugins registry.register_interface(ILayers) registry.register_interface(IAddons) registry.for_interface(ILayers).active_layers =\ frozenset({'plone.server.interfaces.layer.IDefaultLayer'}) roles = IPrincipalRoleManager(self) roles.assignRoleToPrincipal('plone.SiteAdmin', ROOT_USER_ID) roles.assignRoleToPrincipal('plone.Owner', ROOT_USER_ID)
def roles(self, value): principal_id = self.__principal__.id rolemanager = IPrincipalRoleManager(getSite()) for role, setting in value.items(): if role not in self._roles: continue if setting is Allow: rolemanager.assignRoleToPrincipal(role, principal_id) elif setting is Deny: rolemanager.removeRoleFromPrincipal(role, principal_id) else: rolemanager.unsetRoleForPrincipal(role, principal_id)
def anlegen(self): data, errors = self.extractData() if errors: self.flash('Es sind Fehler aufgetreten', type='error') return um = getUtility(IUserManagement) um.addUser(**data) # Setting Home Folder Rights for role in data.get('rollen'): principal_roles = IPrincipalRoleManager(self.context.__parent__[role]) principal_roles.assignRoleToPrincipal('uvc.Editor', data.get('mnr')) self.flash(_(u'Der Mitbenutzer wurde gespeichert')) principal = self.request.principal homeFolder = IHomeFolder(principal).homeFolder self.redirect(self.url(homeFolder, '++enms++'))
def __init__(self, *args, **kwargs): ''' Create an administrator with default login and password ''' super(AuthenticatorPlugin, self).__init__(*args, **kwargs) su = InternalPrincipal(login='******', password='******', title=u'Administrator', description=u'The SuperUser') self['admin'] = su roleMgr = IPrincipalRoleManager(grok.getSite()) for uid, _setting in roleMgr.getPrincipalsForRole('gfn.Administrator'): roleMgr.unsetRoleForPrincipal('gfn.Administrator', 'gfn.'+uid) uid = self.getIdByLogin('admin') roleMgr.assignRoleToPrincipal('gfn.Administrator', 'gfn.'+uid)
async def __call__(self): data = await self.request.json() if '@type' not in data and data['@type'] != 'Site': return ErrorResponse('NotAllowed', 'can not create this type %s' % data['@type'], status=401) if 'title' not in data and not data['title']: return ErrorResponse('NotAllowed', 'We need a title', status=401) if 'id' not in data: return ErrorResponse('NotAllowed', 'We need an id', status=401) if 'description' not in data: data['description'] = '' if data['id'] in self.context: # Already exist return ErrorResponse('NotAllowed', 'Duplicate id', status=401) site = create_content('Site', id=data['id'], title=data['title'], description=data['description']) # Special case we don't want the parent pointer site.__name__ = data['id'] self.context[data['id']] = site site.install() self.request._site_id = site.__name__ user = get_authenticated_user_id(self.request) # Local Roles assign owner as the creator user roleperm = IPrincipalRoleManager(site) roleperm.assignRoleToPrincipal('plone.Owner', user) await notify(ObjectFinallyCreatedEvent(site)) # await notify(ObjectAddedEvent(site, self.context, site.__name__)) resp = {'@type': 'Site', 'id': data['id'], 'title': data['title']} headers = {'Location': self.request.path + data['id']} return Response(response=resp, headers=headers)
def anlegen(self): data, errors = self.extractData() if errors: self.flash('Es sind Fehler aufgetreten', type='error') return um = getUtility(IUserManagement) um.addUser(**data) # Setting Home Folder Rights for role in data.get('rollen'): principal_roles = IPrincipalRoleManager( self.context.__parent__[role]) principal_roles.assignRoleToPrincipal('uvc.Editor', data.get('mnr')) self.flash(_('Der Mitbenutzer wurde gespeichert')) principal = self.request.principal homeFolder = IHomeFolder(principal) self.redirect(self.url(homeFolder, '++enms++'))
def assignHomeFolder(self, principalId, folderName=None, create=None): """See IHomeFolderManager""" # The name of the home folder is folderName, if specified, otherwise # it is the principal id name = folderName or principalId # Make the assignment. self.assignments[principalId] = name # Create a home folder instance, if the correct flags are set. if (create is True) or (create is None and self.createHomeFolder): if name not in self.homeFolderBase: objectToCreate = resolve(self.containerObject) self.homeFolderBase[name] = objectToCreate() principal_roles = IPrincipalRoleManager(self.homeFolderBase[name]) for role in self.homeFolderRole: principal_roles.assignRoleToPrincipal( role, principalId)
def __call__(self, *args): site = getObject(self.context) sm = site.getSiteManager() # устанавливаем утилиту аутентификации if u'authentication' not in sm: pau = zope.pluggableauth.PluggableAuthentication(prefix='bbru.') zope.event.notify(ObjectCreatedEvent(pau)) sm[u'authentication'] = pau sm.registerUtility(pau, IAuthentication) pau = sm.getUtility(IAuthentication) # устанавливаем в утилиту аутентификации # стандартный контейнер для пользователей if u'principals' not in pau: plugin = PrincipalFolder(prefix='principal.') zope.event.notify(ObjectCreatedEvent(plugin)) pau[u'principals'] = plugin pau.authenticatorPlugins += (u'principals',) zope.event.notify(ObjectModifiedEvent(pau)) # устанавливаем в утилиту аутентификации # стандартный контейнер для групп пользователей if u'group' not in pau: groupfolder = GroupFolder(prefix='group.') zope.event.notify(ObjectCreatedEvent(groupfolder)) pau[u'group'] = groupfolder pau.authenticatorPlugins += (u'group',) zope.event.notify(ObjectModifiedEvent(pau)) groupfolder = pau[u'group'] roles = IPrincipalRoleManager(site) # создаем одну предустановленную группу if u'members' not in groupfolder: group = GroupInformation(title=u'members') zope.event.notify(ObjectCreatedEvent(group)) groupfolder[u'members'] = group roles.assignRoleToPrincipal('bbru.Member', 'bbru.group.members') # конфигрируем утилиту подключаемой аутентификации так, чтобы # использовать сессии для хранения удостоверений безопасности if u'Session Credentials' not in pau.credentialsPlugins: pau.credentialsPlugins += (u'Session Credentials',)
def create(self, data): if data['__name__']: self.category_name = data['__name__'] else: self.category_name = data['title'] #interfaces.checkCategoryName(self.category_name, context=self.context) category = Category() del data['__name__'] form.applyChanges(self, category, data) # Grant the current user the Edit permission by assigning him # the quotationtool.Creator role, but only locally in the # context of the newly created object. manager = IPrincipalRoleManager(category) manager.assignRoleToPrincipal('quotationtool.Creator', self.request.principal.id) return category
def applyPermissionsForExistentCoUsers(factory): principal = factory.object createProductFolders(principal) homefolder = IHomeFolder(principal).homeFolder if not homefolder: return um = getUtility(IUserManagement) user = um.getUser(principal.id) rollen = user['rollen'] if user['az'] != '00': pid = "%s-%s" % (user['mnr'], user['az']) else: pid = user['mnr'] if homefolder.__name__ != pid: for pf in homefolder.keys(): if pf in rollen: prm = IPrincipalRoleManager(homefolder.get(pf)) if prm.getSetting('uvc.Editor', pid).getName() == 'Unset': prm.assignRoleToPrincipal('uvc.Editor', pid) uvcsite.log('Give uvc.Editor to %s in folder %s' % (pid, pf))
def setup_site_auth(auth): # setup credentials plugin cred = CookieCredentialsPlugin() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(cred)) cred.loginpagename = 'login' # form is generated with z3c.form so we need long request names cred.loginfield = 'form.widgets.login' cred.passwordfield = 'form.widgets.password' cred.autologinfield = 'form.widgets.autologin' auth[u'Cookie Credentials'] = cred auth.credentialsPlugins += (u'Cookie Credentials', ) site = auth.__parent__.__parent__ prm = IPrincipalRoleManager(site) # setup 'members' member container members = member.MemberContainer() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(members)) auth[u'members'] = members auth.authenticatorPlugins += (u'members', ) # setup 'groups' group container groups = group.GroupContainer(u'groups.') zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(groups)) auth[u'groups'] = groups auth.authenticatorPlugins += (u'groups', ) # setup 'Members' group grp = group.Group(u'Members', u'Members') groups.addGroup('Members', grp) prm.assignRoleToPrincipal(roles.MEMBER, 'groups.Members') # setup 'Administrators' group grp = group.Group(u'Administrators', u'Administrators') groups.addGroup('Administrators', grp) prm.assignRoleToPrincipal(roles.ADMINISTRATOR, 'groups.Administrators')
def create_user(self, site, sm, data, site_roles=(), site_permissions=(), prefix='bbru.principal.', folder_key=u'principals'): auth = sm.getUtility(IAuthentication) principalfolder = auth[folder_key] key = data['login'] # convenient principal = InternalPrincipal( data['login'], data['password'], data.get('title') or data['login'].title(), data.get('description') or u'', data.get('passwordManagerName') or 'SSHA') if key not in principalfolder: principalfolder[key] = principal roles = IPrincipalRoleManager(site) for role in site_roles: roles.assignRoleToPrincipal(role, prefix + data['login']) permissions = IPrincipalPermissionManager(site) for permission in site_permissions: permissions.grantPermissionToPrincipal( permission, prefix + data['login'])
def bootStrapSubscriberDatabase(event): """initialisation of usermanagement utility on first database startup """ if appsetup.getConfigContext().hasFeature('devmode'): logger.info(u"starting bootStrapSubscriberDatabase (org.ict_ok...)") dummy_db, connection, dummy_root, root_folder = \ getInformationFromEvent(event) madePluggableAuthentication = ensureUtility(\ root_folder, IAdmUtilUserManagement, 'AdmUtilUserManagement', AdmUtilUserManagement, copy_to_zlog=False, asObject=True) if isinstance(madePluggableAuthentication, PluggableAuthentication): logger.info(u"bootstrap: Ensure named AdmUtilUserManagement") dcore = IWriteZopeDublinCore(madePluggableAuthentication) dcore.title = u"User Authentication" dcore.created = datetime.utcnow() madePluggableAuthentication.ikName = dcore.title # madePluggableAuthentication.__post_init__() sitem = root_folder.getSiteManager() utils = [ util for util in sitem.registeredUtilities() if util.provided.isOrExtends(IAdmUtilSupervisor) ] instAdmUtilSupervisor = utils[0].component instAdmUtilSupervisor.appendEventHistory(\ u" bootstrap: made AdmUtilUserManagement-Utility") groups = GroupFolder(u'group.') madePluggableAuthentication[u'groups'] = groups principals = PrincipalFolder(u'principal.') madePluggableAuthentication[u'principals'] = principals madePluggableAuthentication.credentialsPlugins = \ (u'Session Credentials', u'No Challenge if Authenticated',) p_user = InternalPrincipal(u'User', u'User', u'Initial User', passwordManagerName="SHA1") p_manager = InternalPrincipal(u'Manager', u'Manager', u'Initial Manager', passwordManagerName="SHA1") p_admin = InternalPrincipal(u'Administrator', u'Administrator', u'Initial Administrator', passwordManagerName="SHA1") p_developer = InternalPrincipal(u'Developer', u'Developer', u'Initial Developer', passwordManagerName="SHA1") principals[u'User'] = p_user principals[u'Manager'] = p_manager principals[u'Administrator'] = p_admin principals[u'Developer'] = p_developer grp_usr = GroupInformation( u'User', u'view & analyse data, generate reports ' u'& leave notes at any object') grp_mgr = GroupInformation( u'Manager', u'search, connect, configure ' u'& delete devices') grp_adm = GroupInformation( u'Administrator', u'install, configure ' u'& administrate System') grp_dvl = GroupInformation( u'Developer', u'individual adaption ' u'& development on System') grp_usr.principals = [u'principal.User'] grp_mgr.principals = [u'principal.Manager'] grp_adm.principals = [u'principal.Administrator'] grp_dvl.principals = [u'principal.Developer'] groups[u'User'] = grp_usr groups[u'Manager'] = grp_mgr groups[u'Administrator'] = grp_adm groups[u'Developer'] = grp_dvl madePluggableAuthentication.authenticatorPlugins = (u'groups', u'principals') prm = IPrincipalRoleManager(root_folder) prm.assignRoleToPrincipal(u'org.ict_ok.usr', u'group.User') prm.assignRoleToPrincipal(u'org.ict_ok.mgr', u'group.Manager') prm.assignRoleToPrincipal(u'org.ict_ok.adm', u'group.Administrator') prm.assignRoleToPrincipal(u'org.ict_ok.dvl', u'group.Developer') transaction.get().commit() connection.close()
def ldap_assing_role_to_manager(event): if isinstance(event.info, LDAPPrincipalInfo): manager = IPrincipalRoleManager(grok.getSite()) manager.assignRoleToPrincipal("mailcone.ldap.authentication", event.principal.id)
def grantCreator(obj): dc = IWriteZopeDublinCore(obj) role_manager = IPrincipalRoleManager(obj) role_manager.assignRoleToPrincipal('quotationtool.Creator', dc.creators[0])
class Ownership(object): adapts(IOwnerAware) implements(IOwnership) def __init__(self, context): self._rolemanager = IPrincipalRoleManager(context) self.context = context def _getCurrentOwnerId(self): settings = self._rolemanager.getPrincipalsForRole(OWNER_ROLE) principals = [ principal_id for (principal_id, setting) in settings if sameProxiedObjects(setting, Allow) ] if not principals: return None if len(principals) > 1: raise RuntimeError( 'Object has multiple owners. This should not happen') return principals[0] @apply def owner(): def fget(self): principal_id = self._getCurrentOwnerId() if principal_id is None: return None try: return getUtility(IAuthentication).getPrincipal(principal_id) except PrincipalLookupError: return None def fset(self, new_owner): if not (new_owner is None or IPrincipal.providedBy(new_owner)): raise ValueError('IPrincipal object or None required') if new_owner is None: new_owner_id = None else: new_owner_id = new_owner.id current_owner_id = self._getCurrentOwnerId() if new_owner_id == current_owner_id: return if current_owner_id is not None: self._rolemanager.unsetRoleForPrincipal( OWNER_ROLE, current_owner_id) current_owner = getUtility(IAuthentication).getPrincipal( current_owner_id) else: current_owner = None if new_owner_id: self._rolemanager.assignRoleToPrincipal( OWNER_ROLE, new_owner_id) notify(OwnerChangedEvent(self.context, new_owner, current_owner)) return property(fget, fset)
def create(self, uid): home = self.container[uid] = self.content_factory() principal_roles = IPrincipalRoleManager(home) for role in self.owner_roles: principal_roles.assignRoleToPrincipal(role, uid) return home
def status(self): setUpWidget(self, 'principal', self.principal_field, IInputWidget) if not self.principal_widget.hasInput(): return u'' try: principal = self.principal_widget.getInputValue() except MissingInputError: return u'' self.principal = principal # Make sure we can use the principal id in a form by base64ing it principal_token = unicode(principal).encode('base64').strip().replace( '=', '_') roles = [role for name, role in getUtilitiesFor(IRole)] roles.sort(lambda x, y: cmp(x.title, y.title)) principal_roles = IPrincipalRoleManager(self.context) self.roles = [] for role in roles: name = principal_token + '.role.'+role.id field = zope.schema.Choice(__name__= name, title=role.title, vocabulary=settings_vocabulary) setUpWidget(self, name, field, IInputWidget, principal_roles.getSetting(role.id, principal)) self.roles.append(getattr(self, name+'_widget')) perms = [perm for name, perm in getUtilitiesFor(IPermission)] perms.sort(lambda x, y: cmp(x.title, y.title)) principal_perms = IPrincipalPermissionManager(self.context) self.permissions = [] for perm in perms: if perm.id == 'zope.Public': continue name = principal_token + '.permission.'+perm.id field = zope.schema.Choice(__name__=name, title=perm.title, vocabulary=settings_vocabulary) setUpWidget(self, name, field, IInputWidget, principal_perms.getSetting(perm.id, principal)) self.permissions.append( getattr(self, name+'_widget')) if 'GRANT_SUBMIT' not in self.request: return u'' for role in roles: name = principal_token + '.role.'+role.id role_widget = getattr(self, name+'_widget') if role_widget.hasInput(): try: setting = role_widget.getInputValue() except MissingInputError: pass else: # Arrgh! if setting is Allow: principal_roles.assignRoleToPrincipal( role.id, principal) elif setting is Deny: principal_roles.removeRoleFromPrincipal( role.id, principal) else: principal_roles.unsetRoleForPrincipal( role.id, principal) for perm in perms: if perm.id == 'zope.Public': continue name = principal_token + '.permission.'+perm.id perm_widget = getattr(self, name+'_widget') if perm_widget.hasInput(): try: setting = perm_widget.getInputValue() except MissingInputError: pass else: # Arrgh! if setting is Allow: principal_perms.grantPermissionToPrincipal( perm.id, principal) elif setting is Deny: principal_perms.denyPermissionToPrincipal( perm.id, principal) else: principal_perms.unsetPermissionForPrincipal( perm.id, principal) return _('Grants updated.')
def grant_homefolder_access(self, uid, homefolder, roles=[]): principal_roles = IPrincipalRoleManager(homefolder) for role in roles: principal_roles.assignRoleToPrincipal(role, uid)
def roles(self, values): prmanager = IPrincipalRoleManager(self.context) for role_id in self.roles: prmanager.unsetRoleForPrincipal(role_id, self.principal_id) for role_id in values: prmanager.assignRoleToPrincipal(role_id, self.principal_id)
def createUtils(root_folder, connection=None, dummy_db=None): madeLdapAdapter = ensureUtility(\ root_folder, IManageableLDAPAdapter, 'ManageableLDAPAdapter', ManageableLDAPAdapter, name='ManageableLDAPAdapter', copy_to_zlog=False) madeLdapPas = ensureUtility(\ root_folder, IMyLDAPAuthentication, 'MyLDAPAuthentication', MyLDAPAuthentication, name='MyLDAPAuthentication', copy_to_zlog=False) if isinstance(madeLdapPas, MyLDAPAuthentication): madeLdapPas.adapterName = 'ManageableLDAPAdapter' madeLdapPas.searchBase = u'ou=staff,o=ikom-online,c=de,o=ifdd' madeLdapPas.searchScope = u'sub' madeLdapPas.groupsSearchBase = u'cn=testIKOMtrol,o=ikom-online,c=de,o=ifdd' madeLdapPas.groupsSearchScope = u'one' madeLdapPas.loginAttribute = u'uid' madeLdapPas.principalIdPrefix = u'principal.' madeLdapPas.idAttribute = u'uid' madeLdapPas.titleAttribute = u'cn' madeLdapPas.groupIdAttribute = u'cn' madePluggableAuthentication = ensureUtility(\ root_folder, IAdmUtilUserManagement, 'AdmUtilUserManagement', AdmUtilUserManagement, name='', copy_to_zlog=False) if isinstance(madePluggableAuthentication, PluggableAuthentication): logger.info(u"bootstrap: Ensure named AdmUtilUserManagement") dcore = IWriteZopeDublinCore(madePluggableAuthentication) dcore.title = u"User Authentication" dcore.created = datetime.utcnow() madePluggableAuthentication.ikName = dcore.title # madePluggableAuthentication.__post_init__() sitem = root_folder.getSiteManager() utils = [ util for util in sitem.registeredUtilities() if util.provided.isOrExtends(IAdmUtilSupervisor) ] instAdmUtilSupervisor = utils[0].component instAdmUtilSupervisor.appendEventHistory(\ u" bootstrap: made AdmUtilUserManagement-Utility") groups = GroupFolder(u'group.') madePluggableAuthentication[u'groups'] = groups principals = PrincipalFolder(u'principal.') madePluggableAuthentication[u'principals'] = principals madePluggableAuthentication.credentialsPlugins = \ (u'Session Credentials', u'No Challenge if Authenticated',) p_user = InternalPrincipal(u'User', u'User', u'Initial User', passwordManagerName="SHA1") p_manager = InternalPrincipal(u'Manager', u'Manager', u'Initial Manager', passwordManagerName="SHA1") p_admin = InternalPrincipal(u'Administrator', u'Administrator', u'Initial Administrator', passwordManagerName="SHA1") p_developer = InternalPrincipal(u'Developer', u'Developer', u'Initial Developer', passwordManagerName="SHA1") principals[u'User'] = p_user principals[u'Manager'] = p_manager principals[u'Administrator'] = p_admin principals[u'Developer'] = p_developer grp_usr = GroupInformation( u'User', u'view & analyse data, generate reports ' u'& leave notes at any object') grp_mgr = GroupInformation( u'Manager', u'search, connect, configure ' u'& delete devices') grp_adm = GroupInformation( u'Administrator', u'install, configure ' u'& administrate System') grp_dvl = GroupInformation( u'Developer', u'individual adaption ' u'& development on System') grp_usr.principals = [u'principal.User'] grp_mgr.principals = [u'principal.Manager'] grp_adm.principals = [u'principal.Administrator'] grp_dvl.principals = [u'principal.Developer'] groups[u'User'] = grp_usr groups[u'Manager'] = grp_mgr groups[u'Administrator'] = grp_adm groups[u'Developer'] = grp_dvl #import pdb #pdb.set_trace() madePluggableAuthentication[u'LDAPAuthentication'] = madeLdapPas madePluggableAuthentication.authenticatorPlugins = \ (u'groups', u'principals', u'LDAPAuthentication') prm = IPrincipalRoleManager(root_folder) prm.assignRoleToPrincipal(u'org.ict_ok.usr', u'group.User') prm.assignRoleToPrincipal(u'org.ict_ok.mgr', u'group.Manager') prm.assignRoleToPrincipal(u'org.ict_ok.adm', u'group.Administrator') prm.assignRoleToPrincipal(u'org.ict_ok.dvl', u'group.Developer') transaction.get().commit() if connection is not None: connection.close()
def grant_role(self, role_id, pids): if isinstance(pids, basestring): pids = [pids] role_id = ROLE_MAP[role_id] prinrole = IPrincipalRoleManager(self.context) for pid in pids: prinrole.assignRoleToPrincipal(role_id, pid)