예제 #1
0
    def _do_cat_acl(self, obj):
        prinrole = IPrincipalRoleManager(obj)
        auth = getUtility(IAuthentication, context=None)

        user_allow = collections.defaultdict(list)
        user_deny = collections.defaultdict(list)
        users = set()
        for role, principal, setting in prinrole.getPrincipalsAndRoles():
            users.add(principal)
            if setting.getName() == 'Allow':
                user_allow[principal].append(role)
            else:
                user_deny[principal].append(role)

        acl = {'allow': [], 'deny': []}

        for principal in users:
            def formatted_perms(perms):
                prin = auth.getPrincipal(principal)
                typ = 'group' if isinstance(prin, Group) else 'user'
                def grants(i):
                    return ','.join('@%s' % i[0] for i in rolePermissionManager.getPermissionsForRole(i)
                                    if i[0] != 'oms.nothing')
                return (typ, principal, ''.join('%s' %
                                                (Role.role_to_nick.get(i, '(%s)' % i))
                                                for i in sorted(perms)))

            if principal in user_allow:
                acl['allow'].append('%s:%s:%s' % formatted_perms(user_allow[principal]))

            if principal in user_deny:
                acl['deny'].append('%s:%s:%s' % formatted_perms(user_deny[principal]))
        return acl
예제 #2
0
    def render(self):
        # Test that our installation was successful
        pau = queryUtility(IAuthentication)
        if pau is None or type(pau) is not PluggableAuthenticatorPlugin:
            if pau is not None:
                st = "PAU not installed correctly: %s" % pau
                utilities = getUtilitiesFor(IAuthentication)
                st += "\n Available utilities are: %s" % [u for u in utilities]
                return st
            else:
                return "PAU Utility not found"

        st = ('Success: Credentials plugins= %s; Authenticator plugins= %s' %
                (pau.credentialsPlugins, pau.authenticatorPlugins))
        roleMgr = IPrincipalRoleManager(self.context)
        p = roleMgr.getPrincipalsForRole('gfn.Administrator')
        st += "\n  Administrators: %s" %p
        for ut in pau.credentialsPlugins:
            if queryUtility(ICredentialsPlugin, name=ut) is None:
                st += '\n     Could not find credentials plugin for %s' % ut
        for ut in pau.authenticatorPlugins:
            if queryUtility(IAuthenticatorPlugin, name=ut) is None:
                st += '\n     Could not find authenticator plugin for %s' % ut

        return st
예제 #3
0
 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)
예제 #4
0
파일: security.py 프로젝트: ilshad/tacklets
def clean_roles(context, role_id, setting=Allow):
    """Remove given role for all principals"""
    prinrole = IPrincipalRoleManager(context)
    old = prinrole.getPrincipalsForRole(role_id)
    for x in old:
        if x[1] == setting:
            prinrole.unsetRoleForPrincipal(role_id, x[0])
예제 #5
0
    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)
예제 #6
0
 def accountFromRoles(self, login):
     ''' Populate self.roles by querying the role manager
     '''
     roleMgr = IPrincipalRoleManager(grok.getSite())
     for rid, setting in roleMgr.getRolesForPrincipal('gfn.'+login):
         if setting.getName() == 'Allow':
             self.roles.add(rid)
예제 #7
0
파일: auth.py 프로젝트: esartor/merlot
 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)
예제 #8
0
 def handle_delete(self):
     data, errors = self.extractData()
     del self.context.__parent__[self.context.__name__]
     role_manager = IPrincipalRoleManager(grok.getSite())
     for role_id, setting in role_manager.getRolesForPrincipal(data['login']):
         role_manager.removeRoleFromPrincipal(role_id, data['login'])
     self.redirect(self.url(grok.getSite(), '/benutzer'))
예제 #9
0
파일: workflow.py 프로젝트: ilshad/tacklets
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)
예제 #10
0
파일: hotfix.py 프로젝트: novareto/uvcsite
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__))
예제 #11
0
파일: setup.py 프로젝트: ilshad/tackle
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))
예제 #12
0
    def roles(self):
        principal_id = self.__principal__.id
        rolemanager = IPrincipalRoleManager(getSite())

        roles = {}
        for rid in self._roles:
            roles[rid] = Unset

        for role, setting in rolemanager.getRolesForPrincipal(principal_id):
            if role in self._roles:
                roles[role] = setting

        return roles
예제 #13
0
 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"
예제 #14
0
파일: enms.py 프로젝트: novareto/uvcsite
 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++'))
예제 #15
0
    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)
예제 #16
0
    def prepare(self):
        results = getUtility(IAcknowledgements).search(object=self.context)

        acknowledged = [i.principal for i in results]
        allusers = searchPrincipals(
            type=('user',),
            principalSubscribed={'any_of': (True,)})

        members = []
        bannedusers = getUtility(IBanPrincipalConfiglet)
        rolemanager = IPrincipalRoleManager(getSite())
        checkroles = ['zope.Anonymous', ]

        portal_roles = getUtility(IPortalRoles)
        if 'site.member' in portal_roles:
            checkroles.append(portal_roles['site.member'].id)

        for pid in [i.id for i in allusers if i.id not in acknowledged]:
            # Note: skip banned users
            if pid in bannedusers.banned:
                continue

            try:
                principal = getPrincipal(pid)
            except PrincipalLookupError:
                continue

            # Note: skip users with Deny roles
            nextitem = False
            for role, setting in rolemanager.getRolesForPrincipal(pid):
                if role == 'zope.Manager':
                    continue
                if role in checkroles and setting == Deny:
                    nextitem = True
                    break
            if nextitem:
                continue

            profile = IPersonalProfile(principal, None)
            if profile is None:
                continue

            members.append(profile)

        return self.export(members)
예제 #17
0
파일: config.py 프로젝트: domashevskiy/bbru
    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',)
예제 #18
0
    def prepare(self):
        results = getUtility(IAcknowledgements).search(object=self.context)

        if len(results) > 0:
            members = []
            # localtz = tz.tzlocal()
            bannedusers = getUtility(IBanPrincipalConfiglet)
            rolemanager = IPrincipalRoleManager(getSite())
            checkroles = ['zope.Anonymous', ]

            portal_roles = getUtility(IPortalRoles)
            if 'site.member' in portal_roles:
                checkroles.append(portal_roles['site.member'].id)

            for pid, ack_date in [(i.principal, i.date) for i in results]:
                # Note: skip banned users
                if pid in bannedusers.banned:
                    continue

                try:
                    principal = getPrincipal(pid)
                except PrincipalLookupError:
                    continue

                # Note: skip users with Deny roles
                nextitem = False
                for role, setting in rolemanager.getRolesForPrincipal(pid):
                    if role == 'zope.Manager':
                        continue
                    if role in checkroles and setting == Deny:
                        nextitem = True
                        break
                if nextitem:
                    continue

                profile = IPersonalProfile(principal, None)
                if profile is None:
                    continue
                members.append(
                    (profile, ack_date.strftime('%Y-%m-%d %H:%M UTC')))
                # NOTE: convert date to local time zone
                # .replace(tzinfo=utc).astimezone(localtz).strftime('%Y-%m-%d %H:%M %Z')

            return self.export(members)
예제 #19
0
 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'))
예제 #20
0
파일: event.py 프로젝트: novareto/uvcsite
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))
예제 #21
0
    def _do_print_acl(self, obj, verbose, recursive, seen):
        prinrole = IPrincipalRoleManager(obj)
        auth = getUtility(IAuthentication, context=None)

        user_allow = collections.defaultdict(list)
        user_deny = collections.defaultdict(list)
        users = set()
        for role, principal, setting in prinrole.getPrincipalsAndRoles():
            users.add(principal)
            if setting.getName() == 'Allow':
                user_allow[principal].append(role)
            else:
                user_deny[principal].append(role)

        for principal in users:
            def formatted_perms(perms):
                prin = auth.getPrincipal(principal)
                typ = 'group' if isinstance(prin, Group) else 'user'
                if verbose:
                    def grants(i):
                        return ','.join('@%s' % i[0] for i in rolePermissionManager.getPermissionsForRole(i)
                                        if i[0] != 'oms.nothing')
                    return (typ, principal, ''.join('%s{%s}' %
                                                    (Role.role_to_nick.get(i, '(%s)' % i), grants(i))
                                                    for i in sorted(perms)))
                else:
                    return (typ, principal, ''.join(Role.role_to_nick.get(i, '(%s)' % i)
                                                    for i in sorted(perms)))

            if principal in user_allow:
                self.write("%s:%s:+%s\n" % formatted_perms(user_allow[principal]))
            if principal in user_deny:
                self.write("%s:%s:-%s\n" % formatted_perms(user_deny[principal]))

        if recursive and IContainer.providedBy(follow_symlinks(obj)):
            for sobj in follow_symlinks(obj).listcontent():
                if follow_symlinks(sobj) not in seen:
                    seen.append(sobj)
                    self.write('%s:\n' % canonical_path(sobj))
                    self._do_print_acl(sobj, verbose, recursive, seen)
예제 #22
0
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)
예제 #23
0
파일: enms.py 프로젝트: novareto/uvcsite
 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)
예제 #24
0
파일: config.py 프로젝트: domashevskiy/bbru
    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'])
예제 #25
0
 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)
예제 #26
0
    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)
예제 #27
0
    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)
예제 #28
0
파일: auth.py 프로젝트: esartor/merlot
 def removeUser(self, username):
     user_folder = grok.getSite()['users']
     if username in user_folder:
         role_manager = IPrincipalRoleManager(grok.getSite())
         role_manager.removeRoleFromPrincipal('merlot.Manager', username)
         del user_folder[username]
예제 #29
0
 def getRoles(self, user):
     manager = IPrincipalRoleManager(self.context)
     setting = manager.getRolesForPrincipal(user)
     return [role[0] for role in setting if role[1] is Allow]
예제 #30
0
 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)
예제 #31
0
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()
예제 #32
0
 def __init__(self, context):
     self._rolemanager = IPrincipalRoleManager(context)
     self.context = context
 def grantCreator(obj):
     dc = IWriteZopeDublinCore(obj)
     role_manager = IPrincipalRoleManager(obj)
     role_manager.assignRoleToPrincipal('quotationtool.Creator',
                                        dc.creators[0])
예제 #34
0
 def borrarUsuario(self, usuario):
     if usuario in self.contenedor_cuentas:
         role_manager = IPrincipalRoleManager(grok.getSite())
         rol = role_manager.getRolesForPrincipal(usuario)[0]
         role_manager.removeRoleFromPrincipal(rol[0], usuario)
         del self.contenedor_cuentas[usuario]
예제 #35
0
 def unset_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.unsetRoleForPrincipal(role_id, pid)
예제 #36
0
 def deny_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.removeRoleFromPrincipal(role_id, pid)
예제 #37
0
 def update(self):
     prm = IPrincipalRoleManager(self.context)
     principals = prm.getPrincipalsForRole('uvc.Editor')
     self.allowed_principals = [x[0] for x in principals if x[1] is Allow]
예제 #38
0
 def delete(self, az):
     cn = '%s-%s' % (self.mnr, az)
     self.um.deleteUser(cn)
     for role in self.__parent__.values():
         principal_roles = IPrincipalRoleManager(role)
         principal_roles.removeRoleFromPrincipal('uvc.Editor', cn)
예제 #39
0
 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
예제 #40
0
파일: security.py 프로젝트: ilshad/tackle
 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)
예제 #41
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)
예제 #42
0
파일: handler.py 프로젝트: novareto/uvcsite
 def getRoles(self, user):
     manager = IPrincipalRoleManager(self.context)
     setting = manager.getRolesForPrincipal(user)
     return [role[0] for role in setting if role[1] is Allow]
예제 #43
0
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()