示例#1
0
    def test_search_users_multi_field(self, mock_search_systemusers_post):
        users = [
            Systemuserreturn(username='******',
                             firstname='David',
                             lastname='Smith',
                             email='*****@*****.**'),
        ]
        mock_search_systemusers_post.return_value = Systemuserslist(
            results=users, total_count=len(users))

        api1 = JumpcloudApiV1("fake_key_123")
        user_search = api1.search_users({
            'firstname': 'David',
            'lastname': 'Smith'
        })
        assert (user_search == [user.to_dict() for user in users])

        call_args, call_kwargs = mock_search_systemusers_post.call_args
        assert (call_kwargs['body']['filter'] == {
            'and': [{
                'firstname': 'David'
            }, {
                'lastname': 'Smith'
            }]
        })
示例#2
0
def delete_system(ctx, system_id):
    """
    Delete a system.
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.delete_system(system_id=system_id)
    click.echo(f"successfully deleted system {system_id}")
示例#3
0
def delete_user(ctx, username):
    """
    Delete a jumpcloud user
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.delete_user(username=username)
    LOGGER.info(f"{response}")
示例#4
0
def get_system(ctx, system_id):
    """
    Detail view of system.
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.get_system(system_id=system_id)
    serialized_response = json.dumps(response, indent=2)
    click.echo(f"{serialized_response}")
示例#5
0
def get_user(ctx, username):
    """
    Detail view of user, outputted in JSON.
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.get_user(username=username)
    serialized_response = json.dumps(response, indent=2)
    LOGGER.info(f"{serialized_response}")
示例#6
0
def set_system(ctx, system_id, **kwargs):
    """
    Set attributes for system with given ID.
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))

    attributes = {key: value for key, value in kwargs.items() if value is not None and value != (None,)}

    response = json.dumps(api1.set_system(system_id=system_id, attributes=attributes), indent=2)
    click.echo(f'{response}')
示例#7
0
    def test_search_users_no_results(self, mock_search_systemusers_post):
        users = []
        mock_search_systemusers_post.return_value = Systemuserslist(results=users, total_count=len(users))

        api1 = JumpcloudApiV1("fake_key_123")
        user_search = api1.search_users({'firstname': 'David'})
        assert (user_search == [])

        call_args, call_kwargs = mock_search_systemusers_post.call_args
        assert (call_kwargs['body'] == {'filter': {'and': [{'firstname': 'David'}]}})
示例#8
0
 def test_get_user_id_not_found(self, mock_search_users):
     response = [{
         'email': '*****@*****.**',
         'firstname': 'JC',
         'lastname': 'Tester1',
         'username': '******'
     }]
     api1 = JumpcloudApiV1("1234")
     mock_search_users.return_value = response
     with pytest.raises(SystemUserNotFoundError):
         api1.get_user_id("foo")
示例#9
0
 def test_set_user_no_id(self, mock_systemusers_list):
     mock_systemusers_list.return_value = [
         {
             'firstname':'Mary',
             'username':'******',
             'email':'*****@*****.**'
         }
     ]
     api1 = JumpcloudApiV1("1234")
     with pytest.raises(SystemUserNotFoundError):
         api1.set_user(username='******', attributes={'email': '*****@*****.**'})
示例#10
0
 def test_get_user_id(self, mock_get_users):
     mock_get_users.return_value = [
         {
             'account_locked': False,
             'activated': False,
             'addresses': [],
             'allow_public_key': True,
             'attributes': [{'name': 'nick', 'value': 'jcman'}],
             'bad_login_attempts': 0,
             'company': None,
             'cost_center': None,
             'created': '2019-11-05T01:42:36.652Z',
             'department': None,
             'description': None,
             'displayname': None,
             'email': '*****@*****.**',
             'employee_identifier': None,
             'employee_type': None,
             'enable_managed_uid': False,
             'enable_user_portal_multifactor': False,
             'external_dn': None,
             'external_source_type': None,
             'externally_managed': False,
             'firstname': 'JC',
             'id': '5dc0d38c1e2e5f51f2312948',
             'job_title': None,
             'lastname': 'Tester1',
             'ldap_binding_user': False,
             'location': None,
             'mfa': {'configured': False, 'exclusion': False, 'exclusion_until': None},
             'middlename': None,
             'organization': '5a9d7329feb7f81004ecbee4',
             'password_expiration_date': None,
             'password_expired': False,
             'password_never_expires': False,
             'passwordless_sudo': False,
             'phone_numbers': [],
             'public_key': None,
             'relationships': [],
             'samba_service_user': False,
             'ssh_keys': [],
             'sudo': False,
             'tags': None,
             'totp_enabled': False,
             'unix_guid': 5109,
             'unix_uid': 5109,
             'username': '******',
         }
     ]
     api1 = JumpcloudApiV1("1234")
     user_id = api1.get_user_id("jctester1")
     assert (
          user_id == "5dc0d38c1e2e5f51f2312948"
     ), "Failed to get the user ID"
示例#11
0
def list_systems(ctx, **kwargs):
    """
    List view of systems. Show systems which match the selected options. Return all systems if no options are selected.
    """
    filter = {}
    for field_name, value in kwargs.items():
        if value is not None:
            filter[field_name] = value

    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.search_systems(filter)
    serialized_response = json.dumps(response, indent=2)
    click.echo(f"{serialized_response}")
示例#12
0
def list_users(ctx, **kwargs):
    """
    List view of users, outputted in JSON
    """
    filter = {}
    for field_name, value in kwargs.items():
        if value:
            filter[field_name] = value

    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    logger = ctx.obj.get('logger')
    response = api1.search_users(filter)
    serialized_response = json.dumps(response, indent=2)
    click.echo(f"{serialized_response}")
示例#13
0
 def test_get_user_no_id(self, mock_systemusers_list):
     users = [
         Systemuserreturn(username='******',
                          firstname='David',
                          email='*****@*****.**'),
         Systemuserreturn(username='******',
                          firstname='Zekun',
                          email='*****@*****.**')
     ]
     mock_systemusers_list.return_value = Systemuserslist(
         results=users, total_count=len(users))
     api1 = JumpcloudApiV1("fake_key_123")
     with pytest.raises(SystemUserNotFoundError):
         api1.get_user('angela')
示例#14
0
def set_user(ctx, username, email, firstname, lastname):
    api1 = JumpcloudApiV1(ctx.obj.get('key'))

    attributes = {}
    if email is not None:
        attributes['email'] = email
    if firstname is not None:
        attributes['firstname'] = firstname
    if lastname is not None:
        attributes['lastname'] = lastname

    response = json.dumps(api1.set_user(username, attributes=attributes),
                          indent=2)
    LOGGER.info(f'{response}')
示例#15
0
def delete_user(info, username):
    """
    Delete a jumpcloud user
    """
    if username is None:
        raise MissingRequiredArgumentError("Deleting a user requires a username")

    api1 = JumpcloudApiV1(info.key)
    click.echo("Delete jumpcloud user " + username)
    id = api1.get_user_id(username)
    if id is None:
        raise SystemUserNotFoundError("System user {} not found".format(username))

    response = api1.delete_user(id)
    click.echo(response)
示例#16
0
 def test_set_user(self, mock_get_user_id, mock_systemusers_put):
     mock_get_user_id.return_value = '1234'
     user = Systemuserreturn(**{
         'email': '*****@*****.**',
         'firstname': 'JC',
         'id': '5ee14bae31771d77fbd4c0e0',
         'lastname': 'Tester3',
         'username': '******'
     })
     mock_systemusers_put.return_value = user
     api1 = JumpcloudApiV1("fake_key_123")
     api_response = api1.set_user("fake_user", {'email': '*****@*****.**'})
     assert (
         api_response == user.to_dict()
     ), "set_user did not correctly call the systemusers_put API method"
示例#17
0
def create_user(ctx, json, file):
    """
    Create a new Jumpcloud user
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    user = {}
    if json is not None:
        user = jccli_helpers.get_user_from_term(json)
    elif file is not None:
        user = jccli_helpers.get_user_from_file(file)
    else:
        raise MissingRequiredArgumentError(
            "SystemUser properties not provided")

    response = api1.create_user(user)
    LOGGER.info(f"{response}")
示例#18
0
def create_user(info, json, file):
    """
    Create a new Jumpcloud user
    """
    api1 = JumpcloudApiV1(info.key)
    user = {}
    if json is not None:
        user = get_user_from_term(json)
    elif file is not None:
        user = get_user_from_file(file)
    else:
        raise MissingRequiredArgumentError("SystemUser properties not provided")

    click.echo("Create jumpcloud user " + user['username'])
    response = api1.create_user(user)
    click.echo(response)
示例#19
0
def list_users(ctx, name):
    """
    List users in a JumpCloud 'user' group
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    api2 = JumpcloudApiV2(ctx.obj.get('key'))
    logger = ctx.obj.get('logger')
    group = api2.get_group(group_name=name, group_type=GroupType.USER_GROUP)
    if group:
        group_id = group['id']
    else:
        logger.error(f"no user group found with name {name}")
        sys.exit(1)
    user_ids = api2.list_group_users(group_id=group_id)
    users = api1.retrieve_users(user_ids=user_ids)
    serialized_response = json.dumps(users, indent=2)
    click.echo(f"{serialized_response}")
示例#20
0
 def test_get_user(self, mock_systemusers_list):
     users = [
         Systemuserreturn(**{
             'username': '******',
             'id': '1234',
             'firstname': 'Steve'
         }),
         Systemuserreturn(**{
             'username': '******',
             'id': '4321',
             'firstname': 'Angela'
         })
     ]
     response = Systemuserslist(results=users, total_count=len(users))
     mock_systemusers_list.return_value = response
     api1 = JumpcloudApiV1("fake_key")
     firstname = api1.get_user(username='******')['firstname']
     assert (firstname == 'Steve'), "Failed to retrieve correct user object"
示例#21
0
def create_user(ctx, username, email, first_name, last_name, allow_public_key,
                ldap_binding_user, passwordless_sudo, sudo):
    """
    Create a new user
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    systemuser = {
        'username': username,
        'email': email,
        'first_name': first_name,
        'last_name': last_name,
        'allow_public_key': str(allow_public_key),
        'ldap_binding_user': str(ldap_binding_user),
        'passwordless_sudo': str(passwordless_sudo),
        'sudo': str(sudo)
    }
    response = json.dumps(api1.create_user(systemuser), indent=2)
    LOGGER.info(f"{response}")
示例#22
0
def set_user(ctx, username, email, firstname, lastname):
    """
    Set user attributes
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))

    attributes = {}
    if email is not None:
        attributes['email'] = email
    if firstname is not None:
        attributes['firstname'] = firstname
    if lastname is not None:
        attributes['lastname'] = lastname

    response = json.dumps(api1.set_user(username, attributes=attributes),
                          indent=2)
    logger = ctx.obj.get('logger')
    click.echo(f'{response}')
示例#23
0
def remove_user(ctx, name, username):
    """
    Remove a user from a JumpCloud 'user' group
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    api2 = JumpcloudApiV2(ctx.obj.get('key'))
    logger = ctx.obj.get('logger')
    try:
        user_id = api1.get_user_id(username)
    except SystemUserNotFoundError:
        logger.error(f"user '{username}' not found")
        sys.exit(1)
    group = api2.get_group(group_name=name, group_type=GroupType.USER_GROUP)
    if group is None:
        logger.error(f"group '{name}' not found")
        sys.exit(1)
    try:
        api2.unbind_user_from_group(user_id, group['id'])
    except ApiException:
        logger.error(f"API exception (confirm that '{username}' is a member of group '{name}')")
        sys.exit(1)
    click.echo(f"Successfully removed user '{username}' from group '{name}'")
示例#24
0
def add_user(ctx, name, username):
    """
    Add a user to a JumpCloud 'user' group
    """
    logger = ctx.obj.get('logger')

    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    api2 = JumpcloudApiV2(ctx.obj.get('key'))
    try:
        user_id = api1.get_user_id(username)
    except SystemUserNotFoundError:
        logger.error(f"user '{username}' not found")
        sys.exit(1)
    group = api2.get_group(group_name=name, group_type=GroupType.USER_GROUP)
    if group is None:
        logger.error(f"no user group named '{name}' could be found")
        sys.exit(1)
    try:
        api2.bind_user_to_group(user_id, group['id'])
    except ApiException:
        logger.error(f"API error (confirm that user {username} has not already been added to group {name}")
        sys.exit(1)
    click.echo(f"Successfully added user '{username}' to group '{name}'")
示例#25
0
def delete_user(ctx, username):
    """
    Delete a user
    """
    api1 = JumpcloudApiV1(ctx.obj.get('key'))
    response = api1.delete_user(username=username)
示例#26
0
def sync_users(key, users):
# pylint: disable-msg=too-many-locals
# pylint: disable-msg=too-many-branches
    """
    Sync data file with jumpcloud
    """
    api1 = JumpcloudApiV1(key)
    api2 = JumpcloudApiV2(key)

    jc_usernames = []
    jc_emails = []
    jc_users = []
    jc_users_request = api1.get_users(limit='')
    if jc_users_request:
        for jc_user in jc_users_request:
            jc_usernames.append(jc_user['_username'])
            jc_emails.append(jc_user['_email'])
            jc_users.append({'username':jc_user['_username'], 'email':jc_user['_email']})

    click.echo("jumpcloud users: " + ','.join(jc_usernames))

    # create new users
    added_users = []
    for user in users:
        do_create_user = False
        try:
            user_name = user['username']
            user_email = user['email']
            if (user_name not in jc_usernames) and (user_email not in jc_emails):
                do_create_user = True
            else:
                click.echo(user_name + " user already exists")
        except KeyError as e:
            raise e

        if do_create_user:
            click.echo("creating user: "******"staff")
            if group_id:
                user_id = api1.get_user_id(user_name)
                click.echo("binding " + user_id + " to group: " + group_id)
                # api2.bind_user_to_group(user_id, group_id)

    # remove users that do not exist in the users file
    local_usernames = []
    local_emails = []
    for user in users:
        local_usernames.append(user['username'])
        local_emails.append(user['email'])

    removed_users = []
    for jc_user in jc_users:
        do_remove_user = False
        user_name = jc_user['username']
        user_email = jc_user['email']
        if (user_name not in local_usernames) and (user_email not in local_emails):
            do_remove_user = True

        if do_remove_user:
            click.echo("removing user: " + user_name)
            removed_users.append(jc_user)
示例#27
0
 def test_delete_user_no_id(self, mock_get_user_id, mock_systemusers_delete):
     mock_get_user_id.return_value = None
     api1 = JumpcloudApiV1("1234")
     with pytest.raises(SystemUserNotFoundError):
         api1.delete_user("foo")
示例#28
0
 def test_delete_user(self, mock_get_user_id, mock_systemusers_delete):
     mock_get_user_id.return_value = "1234"
     api1 = JumpcloudApiV1("1234")
     api1.delete_user("foo")
示例#29
0
def sync_users(ctx, users):
    # pylint: disable-msg=too-many-locals
    # pylint: disable-msg=too-many-branches
    # pylint: disable-msg=too-many-statements
    """
    Sync Jumpcloud users with definition in data file
    :param ctx: Click context
    :param users: users from data file
    :return:
    """
    local_users = users
    key = ctx.obj.get('key')
    dry_run = ctx.params.get('dry_run')

    api1 = JumpcloudApiV1(key)
    jc_usernames = []
    jc_emails = []
    jc_users = []
    jc_users_request = api1.get_users()
    if jc_users_request:
        for jc_user in jc_users_request:
            jc_usernames.append(jc_user['_username'])
            jc_emails.append(jc_user['_email'])
            jc_users.append({
                'username': jc_user['_username'],
                'email': jc_user['_email']
            })

    LOGGER.debug(f"jumpcloud users: {jc_usernames}")

    # create new users
    api2 = JumpcloudApiV2(key)
    added_users = []
    for user in local_users:
        do_create_user = False
        try:
            user_name = user['username']
            user_email = user['email']
            if (user_name not in jc_usernames) and (user_email
                                                    not in jc_emails):
                do_create_user = True
            else:
                LOGGER.debug(f"{user_name} user already exists")
        except KeyError as error:
            raise error

        if do_create_user:
            added_users.append({'username': user_name, 'email': user_email})
            new_user = {}
            new_user['username'] = user_name
            new_user['email'] = user_email
            new_user['firstname'] = user['firstname']
            new_user['firstname'] = user['lastname']
            LOGGER.info(f"create user: {user_name}")
            if not dry_run:
                response = api1.create_user(new_user)
                group_id, group_type = api2.get_group("staff")
                if group_id:
                    user_id = api1.get_user_id(user_name)
                    LOGGER.info(f"bind {user_id} to group: {group_id}")
                    if not dry_run:
                        api2.bind_user_to_group(user_id, group_id)

    # remove users that do not exist in the users file
    local_usernames = []
    local_emails = []
    for user in users:
        local_usernames.append(user['username'])
        local_emails.append(user['email'])

    removed_users = []
    for jc_user in jc_users:
        do_remove_user = False
        user_name = jc_user['username']
        user_email = jc_user['email']
        if (user_name not in local_usernames) and (user_email
                                                   not in local_emails):
            do_remove_user = True

        if do_remove_user:
            removed_users.append(jc_user)
            LOGGER.info(f"remove user: {user_name}")
            if not dry_run:
                response = api1.delete_user(username=user_name)