Get all access keys from a user.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.get_all_access_keys myuser
328036
def get_all_access_keys(user_name, marker=None, max_items=None,
                        region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        return conn.get_all_access_keys(user_name, marker, max_items)
    except boto.exception.BotoServerError as e:
        log.debug(e)
        log.error('Failed to get access keys for IAM user %s.', user_name)
        return six.text_type(e)
960096
def _get_all_permissions(opts, tools):
    """"""
    perms = []
    for tool in tools:
        perms.append((_get_permission_codename(tool, opts), 'Can %s %s' % \
                (tool.name, opts.verbose_name_plural)))
    return perms
765931
def rm_auth_key(user,
                key,
                config='.ssh/authorized_keys',
                fingerprint_hash_type=None):
    '''
    
    '''
    current = auth_keys(user,
                        config=config,
                        fingerprint_hash_type=fingerprint_hash_type)
    linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
    if key in current:
        # Remove the key
        full = _get_config_file(user, config)

        # Return something sensible if the file doesn't exist
        if not os.path.isfile(full):
            return 'Authorized keys file {0} not present'.format(full)

        lines = []
        try:
            # Read every line in the file to find the right ssh key
            # and then write out the correct one. Open the file once
            with salt.utils.files.fopen(full, 'r') as _fh:
                for line in _fh:
                    # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                    line = salt.utils.stringutils.to_unicode(line.strip())
                    if line == '':
                        continue
                    line += '\n'

                    if line.startswith('#'):
                        # Commented Line
                        lines.append(line)
                        continue

                    # get "{options} key"
                    search = re.search(linere, line)
                    if not search:
                        # not an auth ssh key, perhaps a blank line
                        continue

                    comps = search.group(2).split()

                    if len(comps) < 2:
                        # Not a valid line
                        lines.append(line)
                        continue

                    pkey = comps[1]

                    # This is the key we are "deleting", so don't put
                    # it in the list of keys to be re-added back
                    if pkey == key:
                        continue

                    lines.append(line)

            # Let the context manager do the right thing here and then
            # re-open the file in write mode to save the changes out.
            with salt.utils.files.fopen(full, 'wb') as _fh:
                _fh.writelines(salt.utils.data.encode(lines))
        except (IOError, OSError) as exc:
            log.warning('Could not read/write key file: %s',
                        exc)
            return 'Key not removed'
        return 'Key removed'
    # TODO: Should this function return a simple boolean?
    return 'Key not present'
92211
def get_alldictkeys(ddict, parent=None):
    
    parent = [] if parent is None else parent

    if not isinstance(ddict, dict):
        return [tuple(parent)]
    return reduce(
        list.__add__,
        [get_alldictkeys(v, parent + [k]) for k, v in ddict.items()],
        [])
1244276
def get_current_user(self):
        
        if 'Authorization' in self.headers:
            match = self.access_key_regex.search(self.headers['Authorization'])
            if match:
                return match.group(1)

        if self.querystring.get('AWSAccessKeyId'):
            return self.querystring.get('AWSAccessKeyId')
        else:
            # Should we raise an unauthorized exception instead?
            return '111122223333'
860867
def get_all_users(**kwargs):
    
    users_qry = db.DBSession.query(User)

    filter_type = kwargs.get('filter_type')
    filter_value = kwargs.get('filter_value')

    if filter_type is not None:
        # Filtering the search of users
        if filter_type == "id":
            if isinstance(filter_value, str):
                # Trying to read a csv string
                log.info("[HB.users] Getting user by Filter ID : %s", filter_value)
                filter_value = eval(filter_value)
                if type(filter_value) is int:
                    users_qry = users_qry.filter(User.id==filter_value)
                else:
                    users_qry = users_qry.filter(User.id.in_(filter_value))
        elif filter_type == "username":
            if isinstance(filter_value, str):
                # Trying to read a csv string
                log.info("[HB.users] Getting user by Filter Username : %s", filter_value)
                filter_value = filter_value.split(",")
                for i, em in enumerate(filter_value):
                    log.info("[HB.users] >>> Getting user by single Username : %s", em)
                    filter_value[i] = em.strip()
                if isinstance(filter_value, str):
                    users_qry = users_qry.filter(User.username==filter_value)
                else:
                    users_qry = users_qry.filter(User.username.in_(filter_value))
        else:
            raise Exception("Filter type '{}' not allowed".format(filter_type))

    else:
        log.info('[HB.users] Getting All Users')

    rs = users_qry.all()

    return rs
794041
def _get_local_users(self, disabled=None):
        '''
        
        '''
        users = dict()
        path = '/etc/passwd'
        with salt.utils.files.fopen(path, 'r') as fp_:
            for line in fp_:
                line = line.strip()
                if ':' not in line:
                    continue
                name, password, uid, gid, gecos, directory, shell = line.split(':')
                active = not (password == '*' or password.startswith('!'))
                if (disabled is False and active) or (disabled is True and not active) or disabled is None:
                    users[name] = {
                        'uid': uid,
                        'git': gid,
                        'info': gecos,
                        'home': directory,
                        'shell': shell,
                        'disabled': not active
                    }

        return users
1239005
def get_all_group_policies(group_name, region=None, key=None, keyid=None,
                           profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    try:
        response = conn.get_all_group_policies(group_name)
        _list = response.list_group_policies_response.list_group_policies_result
        return _list.policy_names
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return []
618184
def current_access(self):
        
        return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
596554
def passwd_keys(self, username):
        
        keys = []
        if username == 'mysql':
            log("Bad username '%s'" % (username), level=WARNING)

        if username:
            # IMPORTANT: *newer* format must be returned first
            keys.append('mysql-%s.passwd' % (username))
            keys.append('%s.passwd' % (username))
        else:
            keys.append('mysql.passwd')

        for key in keys:
            yield key
93255
def __get_keys(self, name='master', passphrase=None):
        '''
        
        '''
        path = os.path.join(self.opts['pki_dir'],
                            name + '.pem')
        if not os.path.exists(path):
            log.info('Generating %s keys: %s', name, self.opts['pki_dir'])
            gen_keys(self.opts['pki_dir'],
                     name,
                     self.opts['keysize'],
                     self.opts.get('user'),
                     passphrase)
        if HAS_M2:
            key_error = RSA.RSAError
        else:
            key_error = ValueError
        try:
            key = get_rsa_key(path, passphrase)
        except key_error as e:
            message = 'Unable to read key: {0}; passphrase may be incorrect'.format(path)
            log.error(message)
            raise MasterExit(message)
        log.debug('Loaded %s key: %s', name, path)
        return key
72742
def getsshkeys(self):
        
        request = requests.get(
            self.keys_url, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)

        if request.status_code == 200:
            return request.json()
        else:
            return False
318862
def _get_all(self):
        
        return [self._to_dict(row) for row in models.User.objects.all()]
1096141
def accessors(options = {})
      headers = extract_headers!(options)
      json = client.list("/v1/auth/token/accessors", options, headers)
      return Secret.decode(json)
    end
540801
def check_key(user,
              key,
              enc,
              comment,
              options,
              config='.ssh/authorized_keys',
              cache_keys=None,
              fingerprint_hash_type=None):
    '''
    
    '''
    if cache_keys is None:
        cache_keys = []
    enc = _refine_enc(enc)
    current = auth_keys(user,
                        config=config,
                        fingerprint_hash_type=fingerprint_hash_type)
    nline = _format_auth_line(key, enc, comment, options)

    # Removing existing keys from the auth_keys isn't really a good idea
    # in fact
    #
    # as:
    #   - We can have non-salt managed keys in that file
    #   - We can have multiple states defining keys for an user
    #     and with such code only one state will win
    #     the remove all-other-keys war
    #
    # if cache_keys:
    #     for pub_key in set(current).difference(set(cache_keys)):
    #         rm_auth_key(user, pub_key)

    if key in current:
        cline = _format_auth_line(key,
                                  current[key]['enc'],
                                  current[key]['comment'],
                                  current[key]['options'])
        if cline != nline:
            return 'update'
    else:
        return 'add'
    return 'exists'
388520
def keypairs(ctx, user_id, is_active):
    '''
    
    '''
    if ctx.invoked_subcommand is not None:
        return
    fields = [
        ('User ID', 'user_id'),
        ('Access Key', 'access_key'),
        ('Secret Key', 'secret_key'),
        ('Active?', 'is_active'),
        ('Admin?', 'is_admin'),
        ('Created At', 'created_at'),
        ('Last Used', 'last_used'),
        ('Res.Policy', 'resource_policy'),
        ('Rate Limit', 'rate_limit'),
        ('Concur.Limit', 'concurrency_limit'),
        ('Concur.Used', 'concurrency_used'),
    ]
    try:
        user_id = int(user_id)
    except (TypeError, ValueError):
        pass  # string-based user ID for Backend.AI v1.4+
    with Session() as session:
        try:
            items = session.KeyPair.list(user_id, is_active,
                                         fields=(item[1] for item in fields))
        except Exception as e:
            print_error(e)
            sys.exit(1)
        if len(items) == 0:
            print('There are no matching keypairs associated '
                  'with the user ID {0}'.format(user_id))
            return
        print(tabulate((item.values() for item in items),
                       headers=(item[0] for item in fields)))
1224100
def __read_master_key(self):
        '''
        
        '''
        key_user = self.salt_user
        if key_user == 'root':
            if self.opts.get('user', 'root') != 'root':
                key_user = self.opts.get('user', 'root')
        if key_user.startswith('sudo_'):
            key_user = self.opts.get('user', 'root')
        if salt.utils.platform.is_windows():
            # The username may contain '\' if it is in Windows
            # 'DOMAIN\username' format. Fix this for the keyfile path.
            key_user = key_user.replace('\\', '_')
        keyfile = os.path.join(self.opts['cachedir'],
                               '.{0}_key'.format(key_user))
        try:
            # Make sure all key parent directories are accessible
            salt.utils.verify.check_path_traversal(self.opts['cachedir'],
                                                   key_user,
                                                   self.skip_perm_errors)
            with salt.utils.files.fopen(keyfile, 'r') as key:
                return salt.utils.stringutils.to_unicode(key.read())
        except (OSError, IOError, SaltClientError):
            # Fall back to eauth
            return ''