Beispiel #1
0
class LDAPSynchroniser(ldap.LDAPConnectionMixin):
    
    """ This provides complete database synchronisation - either from or to
    the LDAP server. This will synchronise every user and group. It's called
    by the "ldapsync" management command. """
    
    def __init__(self):
        self.conn = self._get_connection()
        self.backend = LDAPBackend()
    
    def ldap_users(self):
        search = settings.ldap_settings.LDAP_PIXIEDUST_ALL_USERS
        for dn, attrs in search.execute(self.conn):
            user_id = attrs[settings.ldap_settings.LDAP_PIXIEDUST_USERNAME_DN_ATTRIBUTE][0]
            yield _LDAPUser(self.backend, username=user_id)
            
    def model_users(self):
        return User.objects.all()
            
    def synchronise_from_ldap(self):
        deactivate()
        for user in self.ldap_users():
            logger.debug("Synchronising %r" % repr(user))
            user._get_or_create_user()
        activate_fromsettings()
            
    def synchronise_to_ldap(self):
        for user in self.model_users():
            ldap_user = self.backend.get_user(user.id)
            sync = SynchronisingUserAdapter(ldap_user)
            logger.debug("Synchronising %r" % repr(user))
            sync.synchronise_groups() # must happen first, because it clears groups!
            sync.synchronise()
            sync.synchronise_profile()
Beispiel #2
0
class LDAPSynchroniser(ldap.LDAPConnectionMixin):
    """ This provides complete database synchronisation - either from or to
    the LDAP server. This will synchronise every user and group. It's called
    by the "ldapsync" management command. """
    def __init__(self):
        self.conn = self._get_connection()
        self.backend = LDAPBackend()

    def ldap_users(self):
        search = settings.ldap_settings.LDAP_PIXIEDUST_ALL_USERS
        for dn, attrs in search.execute(self.conn):
            user_id = attrs[
                settings.ldap_settings.LDAP_PIXIEDUST_USERNAME_DN_ATTRIBUTE][0]
            yield _LDAPUser(self.backend, username=user_id)

    def model_users(self):
        return User.objects.all()

    def synchronise_from_ldap(self):
        deactivate()
        for user in self.ldap_users():
            logger.debug("Synchronising %r" % repr(user))
            user._get_or_create_user()
        activate_fromsettings()

    def synchronise_to_ldap(self):
        for user in self.model_users():
            ldap_user = self.backend.get_user(user.id)
            sync = SynchronisingUserAdapter(ldap_user)
            logger.debug("Synchronising %r" % repr(user))
            sync.synchronise_groups(
            )  # must happen first, because it clears groups!
            sync.synchronise()
            sync.synchronise_profile()
Beispiel #3
0
 def migrate_local_to_ldap(self, request, queryset):
     backend = LDAPBackend()
     for user in queryset:
         # annotate with ldap_user
         user = backend.get_user(user.pk)
         try:
             if user.ldap_user.dn is not None:
                 # replace local password with an invalid one
                 user.password = hashers.make_password(None)
                 user.save(update_fields="password")
                 # populate local record with LDAP values
                 user.ldap_user.populate_user()
             else:
                 self.message_user(
                     request,
                     _("Did not find matching LDAP record for {user}").
                     format(user=user.username),
                     messages.WARNING,
                 )
         except Exception as e:
             logger.exception(f"User migration to LDAP account failed {e}")
             self.message_user(
                 request,
                 _("Failed to migrate {user}").format(user=user.username),
                 messages.ERROR,
             )
Beispiel #4
0
def user_sync_handler(sender, **kwargs):
    instance = kwargs.pop('instance', None)
    created = kwargs.pop('created', None)
    backend = LDAPBackend()
    if sender == User:
        user = backend.get_user(instance.id)
        sync = SynchronisingUserAdapter(user)
        sync.synchronise(created)
Beispiel #5
0
def user_sync_handler(sender, **kwargs):
    instance = kwargs.pop('instance', None)
    created = kwargs.pop('created', None)
    backend = LDAPBackend()
    if sender == User:
        user = backend.get_user(instance.id)
        sync = SynchronisingUserAdapter(user)
        sync.synchronise(created)
Beispiel #6
0
 def update_groups_from_ldap(self, request, queryset):
     backend = LDAPBackend()
     for user in queryset:
         ldap_user = backend.get_user(user.pk)
         try:
             ldap_user.ldap_user._mirror_groups()
         except Exception:
             # _mirror_groups fails when ldap_user is not Active, so delete all groups
             user.groups.clear()
Beispiel #7
0
def reset_ldap_password(username):
    """ Set the user's ldap password to something that can never be entered,
    effectively locking the account. We do not sync these passwords from
    django, because django_auth_ldap sets all new accounts to these
    passwords. """
    
    from django_ldap_pixiedust.user import SynchronisingUserAdapter
    backend = LDAPBackend()
    user = User.objects.get(username=username)
    ldap_user = backend.get_user(user.id)
    sync = SynchronisingUserAdapter(ldap_user)
    sync.reset_ldap_password()
    
Beispiel #8
0
def get_attributes(user, definitions=None, source=None, **kwargs):
    '''
        Return attributes dictionnary

        Dictionnary format:
        attributes = dict()
        data_from_source = list()
        a1 = dict()
                a1['oid'] = definition_name
            Or
                a1['definition'] = definition_name
                    definition may be the definition name like 'gn'
                    or an alias like 'givenName'
            Or
                a1['name'] = attribute_name_in_ns
                a1['namespace'] = ns_name
        a1['values'] = list_of_values
        data_from_source.append(a1)
        ...
        data_from_source.append(a2)
        attributes[source_name] = data_from_source

        First attempt on 'definition' key.
        Else, definition is searched by 'name' and 'namespece' keys.
    '''
    if not user:
        logger.error('get_attributes: No user provided')
        return None
    logger.debug('get_attributes: Searching attributes for user %s' \
        % user)

    from authentic2.attribute_aggregator.models import LdapSource
    sources = None
    if source:
        logger.debug('get_attributes: The required source is %s' % source)
        try:
            sources = [source.ldapsource]
            logger.debug('get_attributes: The source is an LDAP source!')
        except:
            logger.debug('get_attributes: \
                The required source is not a LDAP one')
            return None
    else:
        sources = LdapSource.objects.all()
    if not sources:
        logger.debug('get_attributes: No LDAP source configured')
        return None

    attributes = dict()

    for source in sources:
        logger.debug('get_attributes: The LDAP source is known as %s' \
            % source.name)

        identifier = None
        '''
            Check if the user is authenticated by LDAP.
            If it is, grab the user dn from the LDAPUser object
        '''
        try:
            from django_auth_ldap.backend import LDAPBackend
            backend = LDAPBackend()
            u = backend.get_user(user.id)
            dn = u.ldap_user.dn
            if not dn:
                logger.debug('get_attributes: \
                    User not logged with LDAP')
            else:
                logger.debug('get_attributes: \
                    User logged with dn %s' % dn)
                '''is it logged in that source?'''
                logger.debug('get_attributes: \
                    Is the user logged with the source %s?' % source.name)
                try:
                    l = ldap.open(source.server)
                    l.protocol_version = ldap.VERSION3
                    username = source.user
                    password = source.password
                    if username and password:
                        l.simple_bind(username, password)
                    ldap_result_id = \
                        l.search(dn, ldap.SCOPE_BASE,
                            attrlist=['objectClass'])
                    result_type, result_data = l.result(ldap_result_id, 0)
                    logger.debug('get_attributes: Yes it is, result %s %s' \
                        % (result_type, result_data))
                    identifier = dn
                except ldap.LDAPError, err:
                    logger.debug('get_attributes: \
                        User dn %s unknown in %s or error %s' \
                            % (dn, source.name, str(err)))
        except Exception, err:
            logger.error('get_attributes: \
                Error working with the LDAP backend %s' % str(err))
        if not identifier:
            identifier = get_user_alias_in_source(user, source)
        if not identifier:
            logger.error('get_attributes: \
                No user identifier known into that source')
        else:
            logger.debug('get_attributes: \
                the user is known as %s in source %s' \
                % (identifier, source.name))

            try:
                l = ldap.open(source.server)
                l.protocol_version = ldap.VERSION3
                username = source.user
                password = source.password
                if username and password:
                    l.simple_bind(username, password)
            except ldap.LDAPError, err:
                logger.error('get_attributes: \
                    an error occured at binding due to %s' % err)
            else:
Beispiel #9
0
def get_attributes(user, definitions=None, source=None, **kwargs):
    '''
        Return attributes dictionnary

        Dictionnary format:
        attributes = dict()
        data_from_source = list()
        a1 = dict()
                a1['oid'] = definition_name
            Or
                a1['definition'] = definition_name
                    definition may be the definition name like 'gn'
                    or an alias like 'givenName'
            Or
                a1['name'] = attribute_name_in_ns
                a1['namespace'] = ns_name
        a1['values'] = list_of_values
        data_from_source.append(a1)
        ...
        data_from_source.append(a2)
        attributes[source_name] = data_from_source

        First attempt on 'definition' key.
        Else, definition is searched by 'name' and 'namespece' keys.
    '''
    if not user:
        logger.error('get_attributes: No user provided')
        return None
    logger.debug('get_attributes: Searching attributes for user %s' \
        % user)

    from authentic2.attribute_aggregator.models import LdapSource
    sources = None
    if source:
        logger.debug('get_attributes: The required source is %s' % source)
        try:
            sources = [source.ldapsource]
            logger.debug('get_attributes: The source is an LDAP source!')
        except:
            logger.debug('get_attributes: \
                The required source is not a LDAP one')
            return None
    else:
        sources = LdapSource.objects.all()
    if not sources:
        logger.debug('get_attributes: No LDAP source configured')
        return None

    attributes = dict()

    for source in sources:
        logger.debug('get_attributes: The LDAP source is known as %s' \
            % source.name)

        identifier = None
        '''
            Check if the user is authenticated by LDAP.
            If it is, grab the user dn from the LDAPUser object
        '''
        try:
            from django_auth_ldap.backend import LDAPBackend
            backend = LDAPBackend()
            u = backend.get_user(user.id)
            dn = u.ldap_user.dn
            if not dn:
                logger.debug('get_attributes: \
                    User not logged with LDAP')
            else:
                logger.debug('get_attributes: \
                    User logged with dn %s' % dn)
                '''is it logged in that source?'''
                logger.debug('get_attributes: \
                    Is the user logged with the source %s?' % source.name)
                try:
                    l = ldap.open(source.server)
                    l.protocol_version = ldap.VERSION3
                    username = source.user
                    password = source.password
                    if username and password:
                        l.simple_bind(username, password)
                    ldap_result_id = \
                        l.search(dn, ldap.SCOPE_BASE,
                            attrlist=['objectClass'])
                    result_type, result_data = l.result(ldap_result_id, 0)
                    logger.debug('get_attributes: Yes it is, result %s %s' \
                        % (result_type, result_data))
                    identifier = dn
                except ldap.LDAPError, err:
                    logger.debug('get_attributes: \
                        User dn %s unknown in %s or error %s' \
                            % (dn, source.name, str(err)))
        except Exception, err:
            logger.error('get_attributes: \
                Error working with the LDAP backend %s' %str(err))
        if not identifier:
            identifier = get_user_alias_in_source(user, source)
        if not identifier:
            logger.error('get_attributes: \
                No user identifier known into that source')
        else:
            logger.debug('get_attributes: \
                the user is known as %s in source %s' \
                % (identifier, source.name))

            try:
                l = ldap.open(source.server)
                l.protocol_version = ldap.VERSION3
                username = source.user
                password = source.password
                if username and password:
                    l.simple_bind(username, password)
            except ldap.LDAPError, err:
                logger.error('get_attributes: \
                    an error occured at binding due to %s' % err)
            else: