// FilterUsersWithAuthorizations returns the authorizations granted to an organization
336126
func (m *Manager) FilterUsersWithAuthorizations(usernames []string, organization string) ([]string, error) {
	var auths []Authorization
	err := m.getAuthorizationCollection().Find(bson.M{"username": bson.M{"$in": usernames}, "grantedto": organization}).Select(bson.M{"username": 1}).All(&auths)
	if err != nil {
		return nil, err
	}
	result := []string{}
	for _, auth := range auths {
		result = append(result, auth.Username)
	}
	return result, nil
}
238220
func (l *Limiter) RemoveBasicAuthUsers(basicAuthUsers []string) *Limiter {
	for _, toBeRemoved := range basicAuthUsers {
		l.basicAuthUsers.Delete(toBeRemoved)
	}

	return l
}
1034019
func (a *Agent) filterMembers(token string, members *[]serf.Member) error {
	// Resolve the token and bail if ACLs aren't enabled.
	rule, err := a.resolveToken(token)
	if err != nil {
		return err
	}
	if rule == nil {
		return nil
	}

	// Filter out members based on the node policy.
	m := *members
	for i := 0; i < len(m); i++ {
		node := m[i].Name
		if rule.NodeRead(node) {
			continue
		}
		a.logger.Printf("[DEBUG] agent: dropping node %q from result due to ACLs", node)
		m = append(m[:i], m[i+1:]...)
		i--
	}
	*members = m
	return nil
}
842157
func (tam *TokenAuthorizationMiddleware) IsAuthorized(ctx context.Context, method, path string, tenantId int, tokenInfo *TokenInfo) (bool, error) {
	if tokenInfo == nil {
		return false, errors.New("Invalid token info")
	}

	authAdminRoles, err := tam.isAuthorizedAdminActions(ctx, method, path, tokenInfo.AdminActions())
	if !authAdminRoles || err != nil {
		return authAdminRoles, err
	}

	authTenant, err := tam.isAuthorizedTenantId(ctx, tenantId, tokenInfo.TenantId)
	if !authTenant || err != nil {
		return authTenant, err
	}

	authConfig, err := tam.isAuthorizedConfigNamespace(ctx, path, tokenInfo.TenantId)
	if !authConfig || err != nil {
		return authConfig, err
	}

	// If we're here, then we passed all the tests above and we're good to go
	return true, nil
}
1098100
func (s *AppsService) FindUserInstallation(ctx context.Context, user string) (*Installation, *Response, error) {
	return s.getInstallation(ctx, fmt.Sprintf("users/%v/installation", user))
}
204340
func (api UsersAPI) GetAllAuthorizations(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]

	userMgr := user.NewManager(r)

	authorizations, err := userMgr.GetAuthorizationsByUser(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(authorizations)

}
1264448
func (provider *Provider) IsAuthorized(request *http.Request) (*string, error) {
	var err error
	var userParams map[string]string

	// start with the body/query params
	userParams, err = parseBody(request)
	if err != nil {
		return nil, err
	}

	// if the oauth params are in the Authorization header, grab them, and
	// let them override what's in userParams
	authHeader := request.Header.Get(HTTP_AUTH_HEADER)
	if len(authHeader) > 6 && strings.EqualFold(OAUTH_HEADER, authHeader[0:6]) {
		authHeader = authHeader[6:]
		params := strings.Split(authHeader, ",")
		for _, param := range params {
			vals := strings.SplitN(param, "=", 2)
			k := strings.Trim(vals[0], " ")
			v := strings.Trim(strings.Trim(vals[1], "\""), " ")
			if strings.HasPrefix(k, "oauth") {
				userParams[k], err = url.QueryUnescape(v)
				if err != nil {
					return nil, err
				}
			}
		}
	}

	// pop the request's signature, it's not included in our signature
	// calculation
	oauthSignature, ok := userParams[SIGNATURE_PARAM]
	if !ok {
		return nil, fmt.Errorf("no oauth signature")
	}
	delete(userParams, SIGNATURE_PARAM)

	// get the oauth consumer key
	consumerKey, ok := userParams[CONSUMER_KEY_PARAM]
	if !ok || consumerKey == "" {
		return nil, fmt.Errorf("no consumer key")
	}

	// use it to create a consumer object
	consumer, err := provider.ConsumerGetter(consumerKey, userParams)
	if err != nil {
		return nil, err
	}

	// Make sure timestamp is no more than 10 digits
	timestamp := userParams[TIMESTAMP_PARAM]
	if len(timestamp) > 10 {
		timestamp = timestamp[0:10]
	}

	// Check the timestamp
	if !consumer.serviceProvider.IgnoreTimestamp {
		oauthTimeNumber, err := strconv.Atoi(timestamp)
		if err != nil {
			return nil, err
		}

		if math.Abs(float64(int64(oauthTimeNumber)-provider.clock.Seconds())) > 5*60 {
			return nil, fmt.Errorf("too much clock skew")
		}
	}

	// Include the query string params in the base string
	if consumer.serviceProvider.SignQueryParams {
		for k, v := range request.URL.Query() {
			userParams[k] = strings.Join(v, "")
		}
	}

	// if our consumer supports bodyhash, check it
	if consumer.serviceProvider.BodyHash {
		bodyHash, err := calculateBodyHash(request, consumer.signer)
		if err != nil {
			return nil, err
		}

		sentHash, ok := userParams[BODY_HASH_PARAM]

		if bodyHash == "" && ok {
			return nil, fmt.Errorf("body_hash must not be set")
		} else if sentHash != bodyHash {
			return nil, fmt.Errorf("body_hash mismatch")
		}
	}

	allParams := NewOrderedParams()
	for key, value := range userParams {
		allParams.Add(key, value)
	}

	makeURLAbs(request.URL, request)
	baseString := consumer.requestString(request.Method, canonicalizeUrl(request.URL), allParams)
	err = consumer.signer.Verify(baseString, oauthSignature)
	if err != nil {
		return nil, err
	}

	return &consumerKey, nil
}
347784
func (a *API) FindUsers(filter string) ([]User, error) {
	params := Params{}
	if filter != EmptyFilter {
		params["q"] = filter
	}

	dst := make([]User, 0)
	url := a.BuildURL("/v2/user")
	err := a.Get(url, params, &dst)
	return dst, err
}
766073
func (api OrganizationsAPI) ListUsersWithGrant(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]
	grantString := mux.Vars(r)["grant"]

	grant := grants.Grant(grantString)
	if err := grant.Validate(); err != nil {
		log.Debug("Invalid grant: ", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	grantMgr := grants.NewManager(r)
	grantObjs, err := grantMgr.GetByGrant(grant, globalID)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Failed to look up users with grant: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	usernames := []string{}
	for _, grantObj := range grantObjs {
		usernames = append(usernames, grantObj.Username)
	}

	log.Debug("filtering users to those with an open authorization")
	usernames, err = user.NewManager(r).FilterUsersWithAuthorizations(usernames, globalID)
	if handleServerError(w, "filtering out users without authorization", err) {
		return
	}

	userIdentifiers, err := organization.ConvertUsernamesToIdentifiers(usernames, validationdb.NewManager(r))
	if err != nil {
		log.Error("Failed to convert usernames to identifiers: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(userIdentifiers)
}
454593
func (m *Manager) DeleteAuthorization(username, organization string) (err error) {
	_, err = m.getAuthorizationCollection().RemoveAll(bson.M{"username": username, "grantedto": organization})
	return
}
740704
func FilterValidatedEmails(authorizedMails []user.AuthorizationMap, verifiedMails []user.EmailAddress) []user.AuthorizationMap {
	var e []user.AuthorizationMap
	for _, authorizedMail := range authorizedMails {
		for _, verifiedMail := range verifiedMails {
			if authorizedMail.RealLabel == verifiedMail.Label {
				e = append(e, authorizedMail)
				break
			}
		}
	}
	return e
}
42973
func handleUnauthorized(w http.ResponseWriter, r *http.Request, rule Rule, realm string) int {
	if rule.Redirect != "" {
		replacer := httpserver.NewReplacer(r, nil, "")
		http.Redirect(w, r, replacer.Replace(rule.Redirect), http.StatusSeeOther)
		return http.StatusSeeOther
	}

	w.Header().Add("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"%s\",error=\"invalid_token\"", realm))
	return http.StatusUnauthorized
}
903333
func (s *UserService) FindUsers(ctx context.Context, filter influxdb.UserFilter, opt ...influxdb.FindOptions) ([]*influxdb.User, int, error) {
	// TODO: we'll likely want to push this operation into the database eventually since fetching the whole list of data
	// will likely be expensive.
	os, _, err := s.s.FindUsers(ctx, filter, opt...)
	if err != nil {
		return nil, 0, err
	}

	// This filters without allocating
	// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
	users := os[:0]
	for _, o := range os {
		err := authorizeReadUser(ctx, o.ID)
		if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized {
			return nil, 0, err
		}

		if influxdb.ErrorCode(err) == influxdb.EUnauthorized {
			continue
		}

		users = append(users, o)
	}

	return users, len(users), nil
}
458568
func (e *Enforcer) GetPermissionsForUserInDomain(user string, domain string) [][]string {
	return e.GetFilteredPolicy(0, user, domain)
}
4537
func (api UsersAPI) UpdateAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	authorization := &user.Authorization{}

	if err := json.NewDecoder(r.Body).Decode(authorization); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	userMgr := user.NewManager(r)
	userobj, err := userMgr.GetByName(username)
	if handleServerError(w, "getting user by name", err) {
		return
	}
	verifiedEmails := []user.EmailAddress{}
	if len(authorization.OwnerOf.EmailAddresses) != 0 || len(authorization.ValidatedEmailAddresses) > 0 {
		verifiedEmails, err = api.getValidatedEmails(r, *userobj)
		if handleServerError(w, "getting verified emails", err) {
			return
		}
	}

	verifiedPhones := []user.Phonenumber{}
	if len(authorization.ValidatedPhonenumbers) > 0 {
		verifiedPhones, err = api.getValidatedPhones(r, *userobj)
		if handleServerError(w, "getting verified phone numbers", err) {
			return
		}
	}

	authorization.Username = username
	authorization.GrantedTo = grantedTo
	authorization.Addresses = FilterAuthorizationMaps(authorization.Addresses)
	authorization.EmailAddresses = FilterAuthorizationMaps(authorization.EmailAddresses)
	authorization.ValidatedEmailAddresses = FilterValidatedEmails(FilterAuthorizationMaps(authorization.ValidatedEmailAddresses), verifiedEmails)
	authorization.Phonenumbers = FilterAuthorizationMaps(authorization.Phonenumbers)
	authorization.ValidatedPhonenumbers = FilterValidatedPhones(FilterAuthorizationMaps(authorization.ValidatedPhonenumbers), verifiedPhones)
	authorization.BankAccounts = FilterAuthorizationMaps(authorization.BankAccounts)
	authorization.PublicKeys = FilterAuthorizationMaps(authorization.PublicKeys)
	authorization.DigitalWallet = FilterDigitalWallet(authorization.DigitalWallet)
	authorization.OwnerOf = FilterOwnerOf(authorization.OwnerOf, verifiedEmails)
	authorization.Avatars = FilterAuthorizationMaps(authorization.Avatars)

	existingAuth, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "getting existing authorization", err) {
		return
	}
	if existingAuth != nil {
		// Merge authorizations
		authorization.Merge(existingAuth)
	}

	err = userMgr.UpdateAuthorization(authorization)
	if handleServerError(w, "updating authorization", err) {
		return
	}
	w.Header().Set("Content-type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(authorization)
}
804658
func (s *UserService) FindUsers(ctx context.Context, filter platform.UserFilter, opts ...platform.FindOptions) ([]*platform.User, int, error) {
	return s.FindUsersFn(ctx, filter, opts...)
}
1108631
func filterNonPassing(nodes structs.CheckServiceNodes) structs.CheckServiceNodes {
	n := len(nodes)

	// Make a copy of the cached nodes rather than operating on the cache directly
	out := append(nodes[:0:0], nodes...)

OUTER:
	for i := 0; i < n; i++ {
		node := out[i]
		for _, check := range node.Checks {
			if check.Status != api.HealthPassing {
				out[i], out[n-1] = out[n-1], structs.CheckServiceNode{}
				n--
				i--
				continue OUTER
			}
		}
	}
	return out[:n]
}