示例#1
0
def _get_or_create_ldap_user(ldap_user_dict):
    """Get or create a CKAN user from the data returned by the LDAP server

    @param ldap_user_dict: Dictionary as returned by _find_ldap_user
    @return: The CKAN username of an existing user
    """
    # Look for existing user, and if found return it.
    ldap_user = LdapUser.by_ldap_id(ldap_user_dict['username'])
    if ldap_user:
        # TODO: Update the user detail.
        return ldap_user.user.name
    # Check whether we have a name conflict (based on the ldap name, without mapping it to allowed chars)
    exists = _ckan_user_exists(ldap_user_dict['username'])
    if exists['exists'] and not exists['is_ldap']:
        raise UserConflictError(
            _('There is a username conflict. Please inform the site administrator.'
              ))
    # If a user with the same ckan name already exists but is an LDAP user, this means (given that we didn't
    # find it above) that the conflict arises from having mangled another user's LDAP name. There will not
    # however be a conflict based on what is entered in the user prompt - so we can go ahead. The current
    # user's id will just be mangled to something different.

    # Now get a unique user name, and create the CKAN user and the LdapUser entry.
    user_name = _get_unique_user_name(ldap_user_dict['username'])
    user_dict = {
        'name': user_name,
        'email': ldap_user_dict['email'],
        'password': str(uuid.uuid4())
    }
    if 'fullname' in ldap_user_dict:
        user_dict['fullname'] = ldap_user_dict['fullname']
    if 'about' in ldap_user_dict:
        user_dict['about'] = ldap_user_dict['about']
    ckan_user = p.toolkit.get_action('user_create')(context={
        'ignore_auth': True
    },
                                                    data_dict=user_dict)
    ldap_user = LdapUser(user_id=ckan_user['id'],
                         ldap_id=ldap_user_dict['username'])
    ckan.model.Session.add(ldap_user)
    ckan.model.Session.commit()
    # Add the user to it's group if needed
    if 'ldap.organization.id' in config:
        p.toolkit.get_action('member_create')(
            context={
                'ignore_auth': True
            },
            data_dict={
                'id': config['ldap.organization.id'],
                'object': user_name,
                'object_type': 'user',
                'capacity': config['ldap.organization.role']
            })
    return user_name
示例#2
0
def user_update(next_auth, context, data_dict):
    '''Ensure LDAP users cannot be edited, and name clash with ldap users

    :param next_auth: the next auth function in the chain
    :param context:
    :param data_dict:

    '''
    user_obj = None
    try:
        user_obj = auth.get_user_object(context, data_dict)
    except toolkit.ObjectNotFound:
        pass
    # Prevent edition of LDAP users (if so configured)
    if toolkit.config[
            u'ckanext.ldap.prevent_edits'] and user_obj and LdapUser.by_user_id(
                user_obj.id):
        return {
            u'success': False,
            u'msg': toolkit._(u'Cannot edit LDAP users')
        }
    # Prevent name clashes!
    if u'name' in data_dict and user_obj and user_obj.name != data_dict[
            u'name']:
        ldap_user_dict = find_ldap_user(data_dict[u'name'])
        if ldap_user_dict:
            if len(user_obj.ldap_user) == 0 or user_obj.ldap_user[0].ldap_id != \
                    ldap_user_dict[u'ldap_id']:
                return {
                    u'success': False,
                    u'msg':
                    toolkit._(u'An LDAP user by that name already exists')
                }

    return next_auth(context, data_dict)
示例#3
0
def _get_or_create_ldap_user(ldap_user_dict):
    """Get or create a CKAN user from the data returned by the LDAP server

    @param ldap_user_dict: Dictionary as returned by _find_ldap_user
    @return: The CKAN username of an existing user
    """
    # Look for existing user, and if found return it.
    ldap_user = LdapUser.by_ldap_id(ldap_user_dict['username'])
    if ldap_user:
        # TODO: Update the user detail.
        return ldap_user.user.name
    # Check whether we have a name conflict (based on the ldap name, without mapping it to allowed chars)
    exists = _ckan_user_exists(ldap_user_dict['username'])
    if exists['exists'] and not exists['is_ldap']:
        raise UserConflictError(_('There is a username conflict. Please inform the site administrator.'))
    # If a user with the same ckan name already exists but is an LDAP user, this means (given that we didn't
    # find it above) that the conflict arises from having mangled another user's LDAP name. There will not
    # however be a conflict based on what is entered in the user prompt - so we can go ahead. The current
    # user's id will just be mangled to something different.

    # Now get a unique user name, and create the CKAN user and the LdapUser entry.
    user_name = _get_unique_user_name(ldap_user_dict['username'])
    user_dict = {
        'name': user_name,
        'email': ldap_user_dict['email'],
        'password': str(uuid.uuid4())
    }
    if 'fullname' in ldap_user_dict:
        user_dict['fullname'] = ldap_user_dict['fullname']
    if 'about' in ldap_user_dict:
        user_dict['about'] = ldap_user_dict['about']
    ckan_user = p.toolkit.get_action('user_create')(
        context={'ignore_auth': True},
        data_dict=user_dict
    )
    ldap_user = LdapUser(user_id=ckan_user['id'], ldap_id = ldap_user_dict['username'])
    ckan.model.Session.add(ldap_user)
    ckan.model.Session.commit()
    # Add the user to it's group if needed
    if 'ldap.organization.id' in config:
        p.toolkit.get_action('member_create')(
            context={'ignore_auth': True},
            data_dict={
                'id': config['ldap.organization.id'],
                'object': user_name,
                'object_type': 'user',
                'capacity': config['ldap.organization.role']
            }
        )
    return user_name
示例#4
0
def _ckan_user_exists(user_name):
    """Check if a CKAN user name exists, and if that user is an LDAP user.

    @param user_name: User name to check
    @return: Dictionary defining 'exists' and 'ldap'.
    """
    try:
        user = p.toolkit.get_action('user_show')(data_dict = {'id': user_name})
    except p.toolkit.ObjectNotFound:
        return {'exists': False, 'is_ldap': False}

    ldap_user = LdapUser.by_user_id(user['id'])
    if ldap_user:
        return {'exists': True, 'is_ldap': True}
    else:
        return {'exists': True, 'is_ldap': False}
示例#5
0
def _ckan_user_exists(user_name):
    """Check if a CKAN user name exists, and if that user is an LDAP user.

    @param user_name: User name to check
    @return: Dictionary defining 'exists' and 'ldap'.
    """
    try:
        user = p.toolkit.get_action('user_show')(data_dict = {'id': user_name})
    except p.toolkit.ObjectNotFound:
        return {'exists': False, 'is_ldap': False}

    ldap_user = LdapUser.by_user_id(user['id'])
    if ldap_user:
        return {'exists': True, 'is_ldap': True}
    else:
        return {'exists': True, 'is_ldap': False}
示例#6
0
def ckan_user_exists(user_name):
    '''Check if a CKAN user name exists, and if that user is an LDAP user.

    :param user_name: User name to check
    :returns: Dictionary defining 'exists' and 'ldap'.

    '''
    try:
        user = get_user_dict(user_name)
    except toolkit.ObjectNotFound:
        return {u'exists': False, u'is_ldap': False}

    ldap_user = LdapUser.by_user_id(user[u'id'])
    if ldap_user:
        return {u'exists': True, u'is_ldap': True}
    else:
        return {u'exists': True, u'is_ldap': False}
示例#7
0
def user_update(context, data_dict):
    """Ensure LDAP users cannot be edited, and name clash with ldap users"""
    user_obj = None
    try:
        user_obj = ckan.logic.auth.get_user_object(context, data_dict)
    except ckan.logic.NotFound:
        pass
    # Prevent edition of LDAP users (if so configured)
    if config['ldap.prevent_edits'] and user_obj and LdapUser.by_user_id(user_obj.id):
        return {'success': False, 'msg': _('Cannot edit LDAP users')}
    # Prevent name clashes!
    if 'name' in data_dict and user_obj and user_obj.name != data_dict['name']:
        ldap_user_dict = _find_ldap_user(data_dict['name'])
        if ldap_user_dict:
            if len(user_obj.ldap_user) == 0 or user_obj.ldap_user[0].ldap_id != ldap_user_dict['ldap_id']:
                return {'success': False, 'msg': _('An LDAP user by that name already exists')}

    return ckan_user_update(context, data_dict)
示例#8
0
def get_or_create_ldap_user(ldap_user_dict):
    '''Get or create a CKAN user from the data returned by the LDAP server

    :param ldap_user_dict: Dictionary as returned by _find_ldap_user
    :returns: The CKAN username of an existing user

    '''
    # Look for existing user, and if found return it.
    ldap_user = LdapUser.by_ldap_id(ldap_user_dict[u'username'])
    if ldap_user:
        # TODO: Update the user detail.
        return ldap_user.user.name
    user_dict = {}
    update = False
    # Check whether we have a name conflict (based on the ldap name, without mapping
    # it to allowed chars)
    exists = ckan_user_exists(ldap_user_dict[u'username'])
    if exists[u'exists'] and not exists[u'is_ldap']:
        # If ckanext.ldap.migrate is set, update exsting user_dict.
        if not toolkit.config[u'ckanext.ldap.migrate']:
            raise UserConflictError(
                toolkit.
                _(u'There is a username conflict. Please inform the site administrator.'
                  ))
        else:
            user_dict = get_user_dict(ldap_user_dict[u'username'])
            update = True

    # If a user with the same ckan name already exists but is an LDAP user, this means
    # (given that we didn't find it above) that the conflict arises from having mangled
    # another user's LDAP name. There will not however be a conflict based on what is
    # entered in the user prompt - so we can go ahead. The current user's id will just
    # be mangled to something different.

    # Now get a unique user name (if not "migrating"), and create the CKAN user and
    # the LdapUser entry.
    user_name = user_dict[u'name'] if update else get_unique_user_name(
        ldap_user_dict[u'username'])
    user_dict.update({
        u'name': user_name,
        u'email': ldap_user_dict[u'email'],
        u'password': str(uuid.uuid4())
    })
    if u'fullname' in ldap_user_dict:
        user_dict[u'fullname'] = ldap_user_dict[u'fullname']
    if u'about' in ldap_user_dict:
        user_dict[u'about'] = ldap_user_dict[u'about']
    if update:
        ckan_user = toolkit.get_action(u'user_update')(context={
            u'ignore_auth': True
        },
                                                       data_dict=user_dict)
    else:
        ckan_user = toolkit.get_action(u'user_create')(context={
            u'ignore_auth': True
        },
                                                       data_dict=user_dict)
    ldap_user = LdapUser(user_id=ckan_user[u'id'],
                         ldap_id=ldap_user_dict[u'username'])
    Session.add(ldap_user)
    Session.commit()
    # Add the user to it's group if needed
    if u'ckanext.ldap.organization.id' in toolkit.config:
        toolkit.get_action(u'member_create')(
            context={
                u'ignore_auth': True
            },
            data_dict={
                u'id': toolkit.config[u'ckanext.ldap.organization.id'],
                u'object': user_name,
                u'object_type': u'user',
                u'capacity': toolkit.config[u'ckanext.ldap.organization.role']
            })
    return user_name
示例#9
0
def add_ckan_user(context,data_dict):

    # Lookup Ldap
    if  config.get('ckanext.ldap.uri'):
        cnx = ldap.initialize(config['ckanext.ldap.uri'])
    else:
        raise ValidationError({ 'ckan.ldap.uri': 'not speciifed in development/production.ini'})

    try:
       check_name = data_dict['name']
    except:
       raise ValidationError({ 'name': 'missing; use -d option'})

    if check_name == None or check_name == "":
       raise ValidationError({ 'name': ' is missing; use -d option'})

    if config.get('ckanext.ldap.auth.dn'):
        try:
            cnx.bind_s(config['ckanext.ldap.auth.dn'], config['ckanext.ldap.auth.password'])
        except ldap.SERVER_DOWN:
            log.error('LDAP server is not reachable')
            raise EnvironmentError({ 'LDAP server': 'is not reachable'})
        except ldap.INVALID_CREDENTIALS:
            log.error('LDAP server credentials (ckanext.ldap.auth.dn and ckanext.ldap.auth.password) invalid')
            raise EnvironmentError({ 'LDAP server': 'credentials (ckanext.ldap.auth.dn and ckanext.ldap.auth.password) invalid'})
    #print "Hello"

    filter_str = config['ckanext.ldap.search.filter'].format(login=ldap.filter.escape_filter_chars(data_dict['name']))
    attributes = [config['ckanext.ldap.username']]
    if 'ckanext.ldap.fullname' in config:
        attributes.append(config['ckanext.ldap.fullname'])
    if 'ckanext.ldap.email' in config:
        attributes.append(config['ckanext.ldap.email'])
    try:
        ret = _ldap_search(cnx, filter_str, attributes, non_unique='log')
        if ret is None and 'ckanext.ldap.search.alt' in config:
            filter_str = config['ckanext.ldap.search.alt'].format(login=ldap.filter.escape_filter_chars(data_dict['name']))
            ret = _ldap_search(cnx, filter_str, attributes, non_unique='raise')
    finally:
        cnx.unbind()

    ldap_user_dict = ret
    #print ldap_user_dict

    if not ldap_user_dict:
        raise ValidationError({ data_dict['name']: 'user not found in ldap'})

    # check if we already have an entry in the ldap table
    #print ldap_user_dict
    entry_exits = LdapUser.by_ldap_id(ldap_user_dict['username'])
    if entry_exits:
        raise ValidationError({ ldap_user_dict['username']: '******'})

    # Now get a unique user name, and create the CKAN user
    user_name = _get_unique_user_name(data_dict['name'])

    if 'email' in ldap_user_dict:
        user_mail = ldap_user_dict['email']
    else:
        user_mail = ""
    user_dict = {
        'name': user_name,
        'email': user_mail,
        'password': str(uuid.uuid4())
    }
    if 'fullname' in ldap_user_dict:
        user_dict['fullname'] = ldap_user_dict['fullname']
    if 'about' in ldap_user_dict:
        user_dict['about'] = ldap_user_dict['about']
    ckan_user = plugins.toolkit.get_action('user_create')(
        context={'ignore_auth': False},
        data_dict=user_dict
    )
    #print "Hello2"

    # Add the user to it's group if needed - JUST ONE LDAP SPECIFC ORGANIZATION - not for us; Anja 21.6.17
    if 'ckanext.ldap.organization.id' in config:
        plugins.toolkit.get_action('member_create')(
            context={'ignore_auth': False},
            data_dict={
                'id': config['ckanext.ldap.organization.id'],
                'object': user_name,
                'object_type': 'user',
                'capacity': config['ckanext.ldap.organization.role']
            }
        )

    # Check the users email address and add it to the appropiate organization as Editor
    #print ldap_user_dict['email']
    user_org = _check_mail_org(ldap_user_dict['email'])

    if not user_org:
        # check ccca-extern
        if 'ckanext.iauth.special_org' in config:
            user_org = config.get( 'ckanext.iauth.special_org')
            #print "************ 2"

            #print user_org
            # check if org exists
            try:
                check_org = tk.get_action('organization_show')(context, {'id':user_org})
            except:
                user_org = None
                pass

    #print user_name
    if user_org:
        plugins.toolkit.get_action('member_create')(
            context={'ignore_auth': False},
            data_dict={
                'id': user_org,
                'object': user_name,
                'object_type': 'user',
                'capacity': 'editor'
            }
        )


    #' TODO': check oben if already an entry for ldap_id!!!!!
    # Add LdapUser entry = Database entry with match ckan_id - ldap_id
    ldap_user = LdapUser(user_id=ckan_user['id'], ldap_id = ldap_user_dict['username'])
    ckan.model.Session.add(ldap_user)
    ckan.model.Session.commit()

    if user_org:
        return "Hooray! User " + user_name + " successfully created in CKAN and added as an Editor to the Organization " + user_org.encode('ascii','ignore')
    else:
        return "Hooray! User " + user_name + " successfully created in CKAN (no Organization was applicable)"