Retrieve a list of user role names.

        .. note::

            Database management methods.
323873
def get_user_roles(self, user):
        

        # For SQL: user.roles is list of pointers to Role objects
        if isinstance(self.db_adapter, SQLDbAdapter):
            # user.roles is a list of Role IDs
            user_roles = [role.name for role in user.roles]


        # For others: user.roles is a list of role names
        else:
            # user.roles is a list of role names
            user_roles = user.roles

        return user_roles
861102
def get_user_roles(self, user):
        
        self.project_service.set_auth(self._token_project)
        return self.project_service.get_user_roles(user)
580177
def list_roles(self):
    
        '''
            
        '''

        title = '%s.list_certificates' % self.__class__.__name__

    # send request for list of certificates
        self.printer('Querying AWS for iam roles.')
        try:
            response = self.connection.list_roles()
        except:
            raise AWSConnectionError(title)

    # construct certificate list from response
        role_list = []
        if 'Roles' in response.keys():
            for role in response['Roles']:
                role_list.append(role['RoleName'])

    # report results and return list
        if role_list:
            print_out = 'Found iam roles'
            if len(role_list) > 1:
                print_out += 's'
            from labpack.parsing.grammar import join_words
            print_out += ' %s.' % join_words(role_list)
            self.printer(print_out)
        else:
            self.printer('No iam roles found.')

        self.role_list = role_list
        
        return self.role_list
800753
def list_credentials(self, user=None):
        
        if not user:
            user = self.user
        user_id = utils.get_id(user)
        uri = "users/%s/OS-KSADM/credentials" % user_id
        resp, resp_body = self.method_get(uri)
        return resp_body.get("credentials")
1307163
def _get_policies(self):
        """"""
        username = self._get_username_for_key()
        policies = self.client.list_user_policies(
            UserName=username
        )
        return policies
976801
def list_users(self):
        
        lines = output_lines(self.exec_psql('\\du'))
        return [line.split('|') for line in lines]
887989
def get_roles(username, **kwargs):
    '''
    
    '''
    user = get_user(username)
    if not user:
        return []
    command = 'show user-account {0}'.format(username)
    info = ''
    info = show(command, **kwargs)
    if isinstance(info, list):
        info = info[0]
    roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
    if roles:
        roles = roles.group(1).strip().split(' ')
    else:
        roles = []
    return roles
173962
def get_roles(self):
        

        machines = self.c_resources["machines"]
        result = {}
        for desc in machines:
            roles = utils.get_roles_as_list(desc)
            hosts = self._denormalize(desc)
            for role in roles:
                result.setdefault(role, [])
                result[role].extend(hosts)
        return result
1202548
private static Set<String> extractUserRoles(final UsersType.User user) {
        Set<String> roles = new TreeSet<>();
        if (user == null) {
            return roles;
        }

        if (user.getRoles() != null && !user.getRoles().trim().isEmpty()) {
            String [] rolelist = user.getRoles().trim().split(",");
            for (String role: rolelist) {
                if( role == null || role.trim().isEmpty()) {
                    continue;
                }
                roles.add(role.trim().toLowerCase());
            }
        }

        return roles;
    }
978376
public function getRolesNames ()
		{
			$auth = Yii::$app->getAuthManager();
			$rolesByUser = $auth->getRolesByUser($this->id);
			$roles = ArrayHelper::objectsAttribute($rolesByUser, 'name');

			return $roles;
		}
860729
def add_user_role(self, user, role_name):
        """"""

        # For SQL: user.roles is list of pointers to Role objects
        if isinstance(self.db_adapter, SQLDbAdapter):
            # user.roles is a list of Role IDs
            # Get or add role
            role = self.db_adapter.find_first_object(self.RoleClass, name=role_name)
            if not role:
                role = self.RoleClass(name=role_name)
                self.db_adapter.add_object(role)
            user.roles.append(role)

        # For others: user.roles is a list of role names
        else:
            # user.roles is a list of role names
            user.roles.append(role_name)
457520
protected static function get_roles_name() {
        $roles = role_fix_names(get_all_roles(), \context_system::instance(), ROLENAME_ORIGINAL);
        $rolesnames = array();
        foreach ($roles as $role) {
            $rolesnames[$role->id] = $role->localname;
        }
        return $rolesnames;
    }
1136043
def get_role_members(self, role):
        """"""
        targetRoleDb = AuthGroup.objects(creator=self.client, role=role)
        members = AuthMembership.objects(groups__in=targetRoleDb).only('user')
        return json.loads(members.to_json())
535202
def user_list(user=None, host=None, port=None, maintenance_db=None,
              password=None, runas=None, return_password=False):
    '''
    
    '''

    ret = {}

    ver = _parsed_version(user=user,
                          host=host,
                          port=port,
                          maintenance_db=maintenance_db,
                          password=password,
                          runas=runas)
    if ver:
        if ver >= _LooseVersion('9.1'):
            replication_column = 'pg_roles.rolreplication'
        else:
            replication_column = 'NULL'
        if ver >= _LooseVersion('9.5'):
            rolcatupdate_column = 'NULL'
        else:
            rolcatupdate_column = 'pg_roles.rolcatupdate'
    else:
        log.error('Could not retrieve Postgres version. Is Postgresql server running?')
        return False

    # will return empty string if return_password = False
    _x = lambda s: s if return_password else ''

    query = (''.join([
        'SELECT '
        'pg_roles.rolname as "name",'
        'pg_roles.rolsuper as "superuser", '
        'pg_roles.rolinherit as "inherits privileges", '
        'pg_roles.rolcreaterole as "can create roles", '
        'pg_roles.rolcreatedb as "can create databases", '
        '{0} as "can update system catalogs", '
        'pg_roles.rolcanlogin as "can login", '
        '{1} as "replication", '
        'pg_roles.rolconnlimit as "connections", '
        '(SELECT array_agg(pg_roles2.rolname)'
        '    FROM pg_catalog.pg_auth_members'
        '    JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)'
        '    WHERE pg_auth_members.member = pg_roles.oid) as "groups",'
        'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", '
        'pg_roles.rolconfig  as "defaults variables" '
        , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '),
        'FROM pg_roles '
        , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ')
        , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid')
    ]).format(rolcatupdate_column, replication_column))

    rows = psql_query(query,
                      runas=runas,
                      host=host,
                      user=user,
                      port=port,
                      maintenance_db=maintenance_db,
                      password=password)

    def get_bool(rowdict, key):
        '''
        Returns the boolean value of the key, instead of 't' and 'f' strings.
        '''
        if rowdict[key] == 't':
            return True
        elif rowdict[key] == 'f':
            return False
        else:
            return None

    for row in rows:
        retrow = {}
        for key in ('superuser', 'inherits privileges', 'can create roles',
                    'can create databases', 'can update system catalogs',
                    'can login', 'replication', 'connections'):
            retrow[key] = get_bool(row, key)
        for date_key in ('expiry time',):
            try:
                retrow[date_key] = datetime.datetime.strptime(
                    row[date_key], '%Y-%m-%d %H:%M:%S')
            except ValueError:
                retrow[date_key] = None
        retrow['defaults variables'] = row['defaults variables']
        if return_password:
            retrow['password'] = row['password']
        # use csv reader to handle quoted roles correctly
        retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0]
        ret[row['name']] = retrow

    return ret
221898
def get_roles(self):
        '''
        
        '''
        roles = {}
        paths = self.get_roles_paths()

        for path in paths:
            for entry in os.listdir(path):
                rolepath = os.path.join(path, entry)
                if os.path.isdir(rolepath):
                    roles[entry] = rolepath

        return roles
1187929
private Set<String> getUserRoles(Subject subject) {
        Set<String> userRoles = null;

        // get roles from specified classes
        Set<Principal> principals = subject.getPrincipals();
        if (roleClassNames != null && roleClassNames.size() > 0) {
            for (Principal p : principals) {
                if (roleClassNames.contains(p.getClass().getName())) {
                    if (userRoles == null) userRoles = new HashSet<String>();
                    userRoles.add(p.getName());
                }
            }
        }

        // get roles from specified attributes
        Map<String, Set<String>> attributes =
                SubjectUtils.getAttributes(subject);
        for (String key : attributes.keySet()) {
            if (roleAttributeNames.contains(key)) {
                if (userRoles == null) userRoles = new HashSet<String>();
                userRoles.addAll(attributes.get(key));
            }
        }

        if (userRoles == null) userRoles = Collections.emptySet();
        if (logger.isDebugEnabled()) {
            for (String r : userRoles) {
                logger.debug("found role: {}", r);
            }
        }

        return userRoles;
    }
137430
def get_roles(username):
    '''
    
    '''
    info = sendline('show user-account {0}'.format(username))
    roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
    if roles:
        roles = roles.group(1).strip().split(' ')
    else:
        roles = []
    return roles