Return a string suitable for query against `allowed_roles_and_users`
    field.

    :param principal: It can be :data:`Anonymous`, :data:`Authenticated`,
      or an instance of :class:`User` or :class:`Group`.
556523
def indexable_role(principal):
    
    principal = unwrap(principal)

    if hasattr(principal, "is_anonymous") and principal.is_anonymous:
        # transform anonymous user to anonymous role
        principal = Anonymous

    if isinstance(principal, Role):
        return f"role:{principal.name}"
    elif isinstance(principal, User):
        fmt = "user:{:d}"
    elif isinstance(principal, Group):
        fmt = "group:{:d}"
    else:
        raise ValueError(repr(principal))

    return fmt.format(principal.id)
564796
def users(self):
        
        return Users(url="%s/users" % self.root,
                     securityHandler=self._securityHandler,
                     proxy_url=self._proxy_url,
                     proxy_port=self._proxy_port)
848956
@RequestMapping(value = "/oauth/token_key", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getKey(Principal principal) {
        if ((principal == null || principal instanceof AnonymousAuthenticationToken) && !converter.isPublic()) {
            throw new AccessDeniedException("You need to authenticate to see a shared key");
        }
        Map<String, String> result = converter.getKey();
        return result;
    }
808701
private List<String> getUsersFor(Collection<String> roles){
		List<String> users = new HashList<>();
		for(String role: roles){
			if(roleMembershipRU.containsKey(role))
				users.addAll(roleMembershipRU.get(role));
		}
		return users;
	}
694865
def role_show(endpoint_id, role_id):
    
    client = get_client()

    role = client.get_endpoint_role(endpoint_id, role_id)
    formatted_print(
        role,
        text_format=FORMAT_TEXT_RECORD,
        fields=(
            ("Principal Type", "principal_type"),
            ("Principal", lookup_principal),
            ("Role", "role"),
        ),
    )
1248194
def list_privileges(self, principal_name, principal_type, hiveObject):
    
    self.send_list_privileges(principal_name, principal_type, hiveObject)
    return self.recv_list_privileges()
1126574
def ungrant_role(self, principal, role, object=None):
        """"""
        assert principal
        principal = unwrap(principal)
        session = object_session(object) if object is not None else db.session
        manager = self._current_user_manager(session=session)

        args = {
            "role": role,
            "object": object,
            "anonymous": False,
            "user": None,
            "group": None,
        }
        query = session.query(RoleAssignment)
        query = query.filter(
            RoleAssignment.role == role, RoleAssignment.object == object
        )

        if principal is AnonymousRole or (
            hasattr(principal, "is_anonymous") and principal.is_anonymous
        ):
            args["anonymous"] = True
            query.filter(
                RoleAssignment.anonymous == False,
                RoleAssignment.user == None,
                RoleAssignment.group == None,
            )

        elif isinstance(principal, User):
            args["user"] = principal
            query = query.filter(RoleAssignment.user == principal)
        else:
            args["group"] = principal
            query = query.filter(RoleAssignment.group == principal)

        ra = query.one()
        session.delete(ra)
        audit = SecurityAudit(manager=manager, op=SecurityAudit.REVOKE, **args)
        session.add(audit)
        self._needs_flush()
        self._clear_role_cache(principal)
1117374
public boolean isUserInRole(String role)
    {
        Principal principal = getUserPrincipal();
        if (principal != null)
        {
            UserRealm realm = getHttpResponse().getHttpContext().getRealm();
            if (realm != null) return realm.isUserInRole(principal, role);
        }
        return false;
    }
1053714
def _getRole(self, matchedVars):
        
        role = matchedVars.get(ROLE)
        if role is not None and role.strip() == '':
            role = NULL
        else:
            valid = Authoriser.isValidRoleName(role)
            if valid:
                role = Authoriser.getRoleFromName(role)
            else:
                self.print("Invalid role. Valid roles are: {}".
                           format(", ".join(map(lambda r: r.name, Roles))),
                           Token.Error)
                return False
        return role
1228409
public static String getUserName() throws Exception {
        Subject subject = getRunAsSubjectInternal();
        if (subject == null) {
            return null;
        }
        Set<Principal> principals = subject.getPrincipals();
        Iterator<Principal> principalsIterator = principals.iterator();
        if (principalsIterator.hasNext()) {
            Principal principal = principalsIterator.next();
            return principal.getName();
        }
        return null;
    }
853287
function getRole(user) {
      user = user || getCurrentUser();
      return _.find(userRoles, {role: user.role});
    }
1072223
def permitted_query(self, query, group, operations):
        ''''''
        session = query.session
        models = session.router
        user = group.user
        if user.is_superuser:   # super-users have all permissions
            return query
        roles = group.roles.query()
        roles = group.roles.query()  # query on all roles for group
        # The throgh model for Role/Permission relationship
        throgh_model = models.role.permissions.model
        models[throgh_model].filter(role=roles,
                                    permission__model_type=query.model,
                                    permission__operations=operations)

        # query on all relevant permissions
        permissions = router.permission.filter(model_type=query.model,
                                               level=operations)

        owner_query = query.filter(user=user)
        # all roles for the query model with appropriate permission level
        roles = models.role.filter(model_type=query.model, level__ge=level)
        # Now we need groups which have these roles
        groups = Role.groups.throughquery(
            session).filter(role=roles).get_field('group')
        # I need to know if user is in any of these groups
        if user.groups.filter(id=groups).count():
            # it is, lets get the model with permissions less
            # or equal permission level
            permitted = models.instancerole.filter(
                role=roles).get_field('object_id')
            return owner_query.union(model.objects.filter(id=permitted))
        else:
            return owner_query
463663
@Override
    public PrincipalUser getUser(String username, String password) {
        requireNotDisposed();
        requireArgument(_isUsernameValid(username), MessageFormat.format("Invalid username: {0}", username));

        PrincipalUser result = null;
        String userDn = _findDNForUser(username);

        if (userDn != null && password != null) {
            result = _findPrincipalUser(userDn, username, password);
        }
        return result;
    }
734102
def get_principal_name(graph_object):
        
        if hasattr(graph_object, 'user_principal_name'):
            return graph_object.user_principal_name
        elif hasattr(graph_object, 'service_principal_names'):
            return graph_object.service_principal_names[0]
        elif hasattr(graph_object, 'display_name'):
            return graph_object.display_name
        return ''
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
64995
def _get_roles(self, username):
        
        groups = self._get_groups(username)
        user_roles = self.roles.get_roles(groups)
        cherrypy.log.error(
            msg="user '" + username + "' roles: " + str(user_roles),
            severity=logging.DEBUG,
        )
        return user_roles
644050
def token(self) -> str:
        

        return self.value[0] if self in (Role.USER, Role.ROLE_REMOVE) else self.name