예제 #1
0
 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)
예제 #2
0
    def set_acl(self,
                obj,
                inherit,
                allow_perms,
                deny_perms,
                del_perms,
                recursive=False):
        prinrole = IPrincipalRoleManager(obj)
        auth = getUtility(IAuthentication, context=None)
        obj.inherit_permissions = inherit

        def mod_perm(what, setter, p):
            kind, principal, perms = p.split(':')
            if not perms:
                return

            prin = auth.getPrincipal(principal)
            if isinstance(prin, Group) and kind == 'u':
                self.write(
                    "No such user '%s', it's a group, perhaps you mean 'g:%s:%s'\n"
                    % (principal, principal, perms))
                return
            elif type(prin) is User and kind == 'g':
                self.write(
                    "No such group '%s', it's a user (%s), perhaps you mean 'u:%s:%s'\n"
                    % (principal, prin, principal, perms))
                return

            for perm in perms.strip():
                if perm not in Role.nick_to_role:
                    raise NoSuchPermission(perm)
                role = Role.nick_to_role[perm].id
                self.write("%s permission '%s', principal '%s'\n" %
                           (what, role, principal))
                setter(role, principal)

        def apply_perms(prinrole):
            for p in allow_perms or []:
                mod_perm("Allowing", prinrole.assignRoleToPrincipal, p)

            for p in deny_perms or []:
                mod_perm("Denying", prinrole.removeRoleFromPrincipal, p)

            for p in del_perms or []:
                mod_perm("Unsetting", prinrole.unsetRoleForPrincipal, p)

        apply_perms(prinrole)

        seen = [obj]
        if recursive and IContainer.providedBy(obj):
            for sobj in obj.listcontent():
                if follow_symlinks(sobj) not in seen:
                    prinrole = IPrincipalRoleManager(sobj)
                    sobj.inherit_permissions = inherit
                    seen.append(follow_symlinks(sobj))
                    apply_perms(prinrole)
예제 #3
0
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))
예제 #4
0
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__))
예제 #5
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])
예제 #6
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)
예제 #7
0
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)
예제 #8
0
    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')
예제 #9
0
    def test_homefolder_creation_roles(self):
        from zope.securitypolicy.interfaces import IPrincipalRoleManager

        utility = uvcsite.interfaces.IHomeFolderManager(self.app)
        homefolder = utility.create('lars')

        prm = IPrincipalRoleManager(homefolder)
        for role, setting in prm.getRolesForPrincipal('lars'):
            self.assertTrue(role in utility.owner_roles)
            self.assertEqual(setting, zope.securitypolicy.settings.Allow)
예제 #10
0
 def create(self, data):
     entry = BiblatexEntry()
     entry.entry_type = self.type.name
     form.applyChanges(self, entry, 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(entry)
     manager.assignRoleToPrincipal('quotationtool.Creator',
                                   self.request.principal.id)
     return entry
예제 #11
0
    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
예제 #12
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"
예제 #13
0
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__))
예제 #14
0
    def create(self, data):
        obj = zope.component.createObject(
            'quotationtool.biblatex.biblatexentry.BiblatexEntry')
        form.applyChanges(self, obj, 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(obj)
        manager.assignRoleToPrincipal('quotationtool.Creator',
                                      self.request.principal.id)

        return obj
    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
예제 #16
0
    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)
예제 #17
0
def preload_acl_line(path, permspec, filename='-', lineno='-'):
    obj = traverse1(path[1:])

    if obj is None:
        log.warning('No such object: \'%s\'; file: \'%s\' line: %s', path,
                    filename, lineno)
        return

    if obj.__transient__:
        log.warning(
            "Transient object %s always inherits permissions from its parent",
            path)
        return

    if permspec in ('inherit', 'noinherit'):
        obj.inherit_permissions = (permspec == 'inherit')
        return

    auth = getUtility(IAuthentication, context=None)
    interaction = new_interaction(auth.getPrincipal('root'))
    with interaction:
        prinrole = IPrincipalRoleManager(obj)
        action_map = {
            'allow': prinrole.assignRoleToPrincipal,
            'deny': prinrole.removeRoleFromPrincipal,
            'unset': prinrole.unsetRoleForPrincipal
        }

        parsedspec = permspec.strip().split(':', 3)
        if len(parsedspec) < 4:
            log.error(
                'Format error: not all fields are specified: \'%s\' on line %s',
                filename, lineno)
            return

        permtype, kind, principal, perms = parsedspec

        if not perms:
            log.warning(
                'No permissions specified for object: \'%s\'; file: \'%s\' line: %s',
                path, filename, lineno)
            return

        for perm in perms.strip().split(','):
            if perm not in Role.nick_to_role:
                raise NoSuchPermission(perm)
            role = Role.nick_to_role[perm].id
            log.info('%s \'%s\' on %s (%s) to \'%s\'', permtype, perm, path,
                     obj, principal)
            action_map[permtype](role, principal)
예제 #18
0
    def create(self, data):
        obj = Comment()
        form.applyChanges(self, obj, data)
        obj.source_type = 'html'
        obj.about = removeAllProxies(self.context)

        # 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(obj)
        manager.assignRoleToPrincipal('quotationtool.Creator',
                                      self.request.principal.id)

        return obj
예제 #19
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)
예제 #20
0
def effective_perms(interaction, obj):
    def roles_for(role_manager, obj):
        allowed = []
        for g in effective_principals(interaction):
            for role, setting in role_manager.getRolesForPrincipal(g.id):
                if setting.getName() == 'Allow':
                    allowed.append(role)
        return allowed

    effective_allowed = roles_for(prinroleG, obj)

    with interaction:
        effective_allowed.extend(roles_for(IPrincipalRoleManager(obj), obj))

    return effective_allowed
예제 #21
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)
예제 #22
0
    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)
예제 #23
0
 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++'))
예제 #24
0
    def signUp(self, login, title, password, confirmation):
        if confirmation != password:
            raise UserError(
                _('password-confirmation-error',
                  u"Password and confirmation didn't match"))
        folder = self._signupfolder()
        if login in folder:
            raise UserError(
                _('duplicate-login-error',
                  u"This login has already been chosen."))
        principal_id = folder.signUp(login, password, title)

        role_manager = IPrincipalRoleManager(self.context)
        role_manager = removeSecurityProxy(role_manager)
        for role in folder.signup_roles:
            role_manager.assignRoleToPrincipal(role, principal_id)
        self.request.response.redirect("@@welcome.html")
예제 #25
0
    def create(self, data):
        quotation = zope.component.createObject(self.factory_name)
        form.applyChanges(self, quotation, data)
        quotation.source_type = 'html'

        # We want an object which is not security proxied as reference
        # attribute:
        quotation.reference = removeAllProxies(self.context)

        # 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(quotation)
        manager.assignRoleToPrincipal('quotationtool.Creator',
                                      self.request.principal.id)

        return quotation
예제 #26
0
async def sharing_post(context, request):
    data = await request.json()
    roleperm = IRolePermissionManager(context)
    prinrole = IPrincipalRoleManager(context)
    if 'prinrole' not in data and 'roleperm' not in data:
        raise AttributeError('prinrole or roleperm missing')

    if 'prinrole' in data:
        for user, roles in data['prinrole'].items():
            for role in roles:
                prinrole.assignRoleToPrincipal(role, user)

    if 'roleperm' in data:
        for role, perms in data['roleperm'].items():
            for perm in perms:
                roleperm.grantPermissionToRole(perm, role)
    await notify(ObjectPermissionsModifiedEvent(context))
예제 #27
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)
    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
예제 #29
0
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
예제 #30
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)