Beispiel #1
0
    def execute(self, *keys, **options):
        '''
        A stage entry may be taken from the Delete container.
        In that case we rather do 'MODRDN' than 'ADD'.
        '''
        if options.get('from_delete'):
            ldap = self.obj.backend

            staging_dn = self.obj.get_dn(*keys, **options)
            delete_dn = DN(staging_dn[0], self.obj.delete_container_dn, api.env.basedn)

            # Check that this value is a Active user
            try:
                entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(delete_dn, ['dn'])
            except errors.NotFound:
                raise
            self._exc_wrapper(keys, options, ldap.move_entry_newsuperior)(delete_dn, str(DN(self.obj.stage_container_dn, api.env.basedn)))

            entry_attrs = entry_to_dict(entry_attrs, **options)
            entry_attrs['dn'] = delete_dn

            if self.obj.primary_key and keys[-1] is not None:
                return dict(result=entry_attrs, value=keys[-1])
            return dict(result=entry_attrs, value=u'')
        else:
            return super(stageuser_add, self).execute(*keys, **options)
Beispiel #2
0
    def execute(self, cn, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)

        if not options['ipasudoopt'].strip():
            raise errors.EmptyModlist()
        entry_attrs = ldap.get_entry(dn, ['ipasudoopt'])

        try:
            if options['ipasudoopt'] not in entry_attrs['ipasudoopt']:
                entry_attrs.setdefault('ipasudoopt', []).append(
                    options['ipasudoopt'])
            else:
                raise errors.DuplicateEntry
        except KeyError:
            entry_attrs.setdefault('ipasudoopt', []).append(
                options['ipasudoopt'])
        try:
            ldap.update_entry(entry_attrs)
        except errors.EmptyModlist:
            pass
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        attrs_list = self.obj.default_attributes
        entry_attrs = ldap.get_entry(dn, attrs_list)

        entry_attrs = entry_to_dict(entry_attrs, **options)

        return dict(result=entry_attrs, value=pkey_to_value(cn, options))
Beispiel #3
0
    def execute(self, *keys, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(*keys, **options)

        def_values = {}
        # if reseting policy for a user - just his values
        if keys[-1] is not None:
            for a in self.obj.default_attributes:
                def_values[a] = None
        # if reseting global policy - set values to default
        else:
            def_values = _default_values

        entry = ldap.get_entry(dn, def_values.keys())
        entry.update(def_values)
        try:
            ldap.update_entry(entry)
        except errors.EmptyModlist:
            pass

        if keys[-1] is not None:
            # policy for user was deleted, retrieve global policy
            dn = self.obj.get_dn(None)
        entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)

        entry_attrs = entry_to_dict(entry_attrs, **options)

        return dict(result=entry_attrs, value=pkey_to_value(keys[-1], options))
Beispiel #4
0
    def execute(self, cn, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)

        if not options['ipasudoopt'].strip():
            raise errors.EmptyModlist()
        entry_attrs = ldap.get_entry(dn, ['ipasudoopt'])

        try:
            if options['ipasudoopt'] not in entry_attrs['ipasudoopt']:
                entry_attrs.setdefault('ipasudoopt', []).append(
                    options['ipasudoopt'])
            else:
                raise errors.DuplicateEntry
        except KeyError:
            entry_attrs.setdefault('ipasudoopt', []).append(
                options['ipasudoopt'])
        try:
            ldap.update_entry(entry_attrs)
        except errors.EmptyModlist:
            pass
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        attrs_list = self.obj.default_attributes
        entry_attrs = ldap.get_entry(dn, attrs_list)

        entry_attrs = entry_to_dict(entry_attrs, **options)

        return dict(result=entry_attrs, value=pkey_to_value(cn, options))
Beispiel #5
0
    def execute(self, *keys, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(*keys, **options)

        def_values = {}
        # if reseting policy for a user - just his values
        if keys[-1] is not None:
            for a in self.obj.default_attributes:
                def_values[a] = None
        # if reseting global policy - set values to default
        else:
            def_values = _default_values

        entry = ldap.get_entry(dn, def_values.keys())
        entry.update(def_values)
        try:
            ldap.update_entry(entry)
        except errors.EmptyModlist:
            pass

        if keys[-1] is not None:
            # policy for user was deleted, retrieve global policy
            dn = self.obj.get_dn(None)
        entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)

        entry_attrs = entry_to_dict(entry_attrs, **options)

        return dict(result=entry_attrs, value=pkey_to_value(keys[-1], options))
Beispiel #6
0
    def execute(self, *keys, **options):
        '''
        A stage entry may be taken from the Delete container.
        In that case we rather do 'MODRDN' than 'ADD'.
        '''
        if options.get('from_delete'):
            ldap = self.obj.backend

            staging_dn = self.obj.get_dn(*keys, **options)
            delete_dn = DN(staging_dn[0], self.obj.delete_container_dn,
                           api.env.basedn)

            # Check that this value is a Active user
            try:
                entry_attrs = self._exc_wrapper(keys, options,
                                                ldap.get_entry)(delete_dn,
                                                                ['dn'])
            except errors.NotFound:
                raise
            self._exc_wrapper(keys, options, ldap.move_entry_newsuperior)(
                delete_dn, str(DN(self.obj.stage_container_dn,
                                  api.env.basedn)))

            entry_attrs = entry_to_dict(entry_attrs, **options)
            entry_attrs['dn'] = delete_dn

            if self.obj.primary_key and keys[-1] is not None:
                return dict(result=entry_attrs, value=keys[-1])
            return dict(result=entry_attrs, value=u'')
        else:
            return super(stageuser_add, self).execute(*keys, **options)
Beispiel #7
0
    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        # Check to see if the automember rule exists
        try:
            ldap.get_entry(dn, [])
        except errors.NotFound:
            raise errors.NotFound(reason=_(u'Auto member rule: %s not found!') % keys[0])

        # Define container key
        type_attr_default = {'group': 'manager', 'hostgroup': 'fqdn'}
        if 'key' in options:
            key = options['key']
        else:
            key = type_attr_default[options['type']]

        key = '%s=' % key
        completed = 0
        failed = {'failed': {}}

        # Check to see if there are existing exclusive conditions present.
        dn = ldap.get_entry(dn, [EXCLUDE_RE]).dn

        for attr in (INCLUDE_RE, EXCLUDE_RE):
            failed['failed'][attr] = []
            if attr in options and options[attr]:
                entry_attrs[attr] = [key + condition for condition in options[attr]]
                entry_attrs_ = ldap.get_entry(dn, [attr])
                old_entry = entry_attrs_.get(attr, [])
                for regex in entry_attrs[attr]:
                    if regex in old_entry:
                        old_entry.remove(regex)
                        completed += 1
                    else:
                        failed['failed'][attr].append(regex)
                entry_attrs[attr] = old_entry

        entry_attrs = entry_to_dict(entry_attrs, **options)

        # Set failed and completed to they can be harvested in the execute super
        setattr(context, 'failed', failed)
        setattr(context, 'completed', completed)
        setattr(context, 'entry_attrs', entry_attrs)

        # Make sure to returned the failed results if there is nothing to remove
        if completed == 0:
            ldap.get_entry(dn, attrs_list)
            raise errors.EmptyModlist
        return dn
Beispiel #8
0
    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        # Check to see if the automember rule exists
        try:
            dn = ldap.get_entry(dn, []).dn
        except errors.NotFound:
            raise errors.NotFound(reason=_(u'Auto member rule: %s not found!') % keys[0])
        # Define container key
        key = options['key']
        # Check to see if the attribute is valid
        self.obj.check_attr(key)

        key = '%s=' % key
        completed = 0
        failed = {'failed': {}}

        for attr in (INCLUDE_RE, EXCLUDE_RE):
            failed['failed'][attr] = []
            if attr in options and options[attr]:
                entry_attrs[attr] = [key + condition for condition in options[attr]]
                completed += len(entry_attrs[attr])
                try:
                    old_entry = ldap.get_entry(dn, [attr])
                    for regex in old_entry.keys():
                        if not isinstance(entry_attrs[regex], (list, tuple)):
                            entry_attrs[regex] = [entry_attrs[regex]]
                        duplicate = set(old_entry[regex]) & set(entry_attrs[regex])
                        if len(duplicate) > 0:
                            completed -= 1
                        else:
                            entry_attrs[regex] = list(entry_attrs[regex]) + old_entry[regex]
                except errors.NotFound:
                    failed['failed'][attr].append(regex)

        entry_attrs = entry_to_dict(entry_attrs, **options)

        # Set failed and completed to they can be harvested in the execute super
        setattr(context, 'failed', failed)
        setattr(context, 'completed', completed)
        setattr(context, 'entry_attrs', entry_attrs)

        # Make sure to returned the failed results if there is nothing to remove
        if completed == 0:
            ldap.get_entry(dn, attrs_list)
            raise errors.EmptyModlist
        return dn
def test_entry_to_dict():
    class FakeAttributeType(object):
        def __init__(self, name, syntax):
            self.names = (name,)
            self.syntax = syntax

    class FakeSchema(object):
        def get_obj(self, type, name):
            if type != ldap.schema.AttributeType:
                return
            if name == 'binaryattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.40')
            elif name == 'textattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.15')
            elif name == 'dnattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.12')

    class FakeLDAPClient(ipaldap.LDAPClient):
        def __init__(self):
            super(FakeLDAPClient, self).__init__('ldap://test',
                                                 force_schema_updates=False)
            self._has_schema = True
            self._schema = FakeSchema()

    conn = FakeLDAPClient()
    rights = {'nothing': 'is'}

    entry = ipaldap.LDAPEntry(
        conn,
        DN('cn=test'),
        textattr=[u'text'],
        dnattr=[DN('cn=test')],
        binaryattr=['\xffabcd'],
        attributelevelrights=rights)
    the_dict = {
        u'dn': u'cn=test',
        u'textattr': [u'text'],
        u'dnattr': [u'cn=test'],
        u'binaryattr': ['\xffabcd'],
        u'attributelevelrights': rights}
    assert_deepequal(
        baseldap.entry_to_dict(entry, all=True, raw=True),
        the_dict)
def test_entry_to_dict():
    class FakeAttributeType(object):
        def __init__(self, name, syntax):
            self.names = (name, )
            self.syntax = syntax

    class FakeSchema(object):
        def get_obj(self, type, name):
            if type != ldap.schema.AttributeType:
                return
            if name == 'binaryattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.40')
            elif name == 'textattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.15')
            elif name == 'dnattr':
                return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.12')

    class FakeLDAPClient(ipaldap.LDAPClient):
        def __init__(self):
            super(FakeLDAPClient, self).__init__('ldap://test',
                                                 force_schema_updates=False)
            self._has_schema = True
            self._schema = FakeSchema()

    conn = FakeLDAPClient()
    rights = {'nothing': 'is'}

    entry = ipaldap.LDAPEntry(conn,
                              DN('cn=test'),
                              textattr=[u'text'],
                              dnattr=[DN('cn=test')],
                              binaryattr=['\xffabcd'],
                              attributelevelrights=rights)
    the_dict = {
        u'dn': u'cn=test',
        u'textattr': [u'text'],
        u'dnattr': [u'cn=test'],
        u'binaryattr': ['\xffabcd'],
        u'attributelevelrights': rights
    }
    assert_deepequal(baseldap.entry_to_dict(entry, all=True, raw=True),
                     the_dict)
Beispiel #11
0
    def execute(self, *args, **options):

        ldap = self.obj.backend

        staging_dn = self.obj.get_dn(*args, **options)
        assert isinstance(staging_dn, DN)

        # retrieve the current entry
        try:
            entry_attrs = self._exc_wrapper(args, options, ldap.get_entry)(
                staging_dn, ['*']
            )
        except errors.NotFound:
            self.obj.handle_not_found(*args)
        entry_attrs = dict((k.lower(), v) for (k, v) in entry_attrs.iteritems())

        # Check it does not exist an active entry with the same RDN
        active_dn = DN(staging_dn[0], api.env.container_user, api.env.basedn)
        try:
            test_entry_attrs = self._exc_wrapper(args, options, ldap.get_entry)(
                active_dn, ['dn']
            )
            assert isinstance(staging_dn, DN)
            raise errors.DuplicateEntry(
                message=_('active user with name "%(user)s" already exists') %
                dict(user=args[-1]))
        except errors.NotFound:
            pass

        # Check the original entry is valid
        self._check_validy(staging_dn, entry_attrs)

        # Time to build the new entry
        result_entry = {'dn' : active_dn}
        new_entry_attrs = self.__dict_new_entry()
        for (attr, values) in entry_attrs.iteritems():
            self.__merge_values(args, options, entry_attrs, new_entry_attrs, attr)
            result_entry[attr] = values

        # Allow Managed entry plugin to do its work
        if 'description' in new_entry_attrs and NO_UPG_MAGIC in new_entry_attrs['description']:
            new_entry_attrs['description'].remove(NO_UPG_MAGIC)
            if result_entry['description'] == NO_UPG_MAGIC:
                del result_entry['description']

        for (k,v) in new_entry_attrs.iteritems():
            self.log.debug("new entry: k=%r and v=%r)"  % (k, v))

        self._build_new_entry(ldap, staging_dn, entry_attrs, new_entry_attrs)

        # Add the Active entry
        entry = ldap.make_entry(active_dn, new_entry_attrs)
        self._exc_wrapper(args, options, ldap.add_entry)(entry)

        # Now delete the Staging entry
        try:
            self._exc_wrapper(args, options, ldap.delete_entry)(staging_dn)
        except:
            try:
                self.log.error("Fail to delete the Staging user after activating it %s " % (staging_dn))
                self._exc_wrapper(args, options, ldap.delete_entry)(active_dn)
            except:
                self.log.error("Fail to cleanup activation. The user remains active %s" % (active_dn))
                pass
            raise

        # add the user we just created into the default primary group
        config = ldap.get_ipa_config()
        def_primary_group = config.get('ipadefaultprimarygroup')
        group_dn = self.api.Object['group'].get_dn(def_primary_group)

        # if the user is already a member of default primary group,
        # do not raise error
        # this can happen if automember rule or default group is set
        try:
            ldap.add_entry_to_group(active_dn, group_dn)
        except errors.AlreadyGroupMember:
            pass

        # Now retrieve the activated entry
        result_entry = self._exc_wrapper(args, options, ldap.get_entry)(active_dn)
        result_entry = entry_to_dict(result_entry, **options)
        result_entry['dn'] = active_dn

        return dict(result=result_entry,
                    summary=unicode(_('Stage user %s activated' % staging_dn[0].value)),
                    value=pkey_to_value(args[-1], options))