//FilterAuthorizedScopes filters the requested scopes to the ones that are authorizated, if no authorization exists, authorizedScops is nil
540485
func (service *Service) FilterAuthorizedScopes(r *http.Request, username string, grantedTo string, requestedscopes []string) (authorizedScopes []string, err error) {
	authorization, err := userdb.NewManager(r).GetAuthorization(username, grantedTo)
	if authorization == nil || err != nil {
		return
	}

	authorizedScopes = authorization.FilterAuthorizedScopes(requestedscopes)

	return
}
781797
func filterUnauthorizedBuildersFromConsoles(c context.Context, cons []*common.Console) error {
	buckets := stringset.New(0)
	for _, con := range cons {
		buckets = buckets.Union(con.Buckets())
	}
	perms, err := common.BucketPermissions(c, buckets.ToSlice()...)
	if err != nil {
		return err
	}
	for _, con := range cons {
		con.FilterBuilders(perms)
	}
	return nil
}
1283802
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) (as []*platform.Authorization, i int, err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error finding authorizations", zap.Error(err))
		}
	}()

	return s.AuthorizationService.FindAuthorizations(ctx, filter, opt...)
}
692461
func (c *Client) FilterDhcp(scope string, data interface{}) (interface{}, error) {
	return c.AccessFilter("filter_dhcp", scope, data)
}
476716
func (s *Service) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) ([]*platform.Authorization, int, error) {
	op := OpPrefix + platform.OpFindAuthorizations
	if filter.ID != nil {
		a, err := s.FindAuthorizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &platform.Error{
				Err: err,
				Op:  op,
			}
		}

		return []*platform.Authorization{a}, 1, nil
	}

	var as []*platform.Authorization
	if filter.User != nil {
		u, err := s.findUserByName(ctx, *filter.User)
		if err != nil {
			return nil, 0, &platform.Error{
				Op:  op,
				Err: err,
			}
		}
		filter.UserID = &u.ID
	}

	if filter.Org != nil {
		o, err := s.findOrganizationByName(ctx, *filter.Org)
		if err != nil {
			return nil, 0, &platform.Error{
				Op:  op,
				Err: err,
			}
		}
		filter.OrgID = &o.ID
	}

	var err error
	filterF := filterAuthorizationsFn(filter)
	s.authorizationKV.Range(func(k, v interface{}) bool {
		a, ok := v.(platform.Authorization)
		if !ok {
			err = &platform.Error{
				Code: platform.EInternal,
				Msg:  "value found in map is not an authorization",
				Op:   op,
			}
			return false
		}

		if filterF(&a) {
			as = append(as, &a)
		}

		return true
	})

	if err != nil {
		return nil, 0, err
	}

	return as, len(as), nil
}
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
}
1007034
func (s *storage) RemoveAuthorize(code string) error {
	// TODO: return no error if registry returns IsNotFound
	return s.authorizetoken.Delete(code, nil)
}
312234
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter influxdb.AuthorizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Authorization, 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.
	as, _, err := s.s.FindAuthorizations(ctx, filter, opt...)
	if err != nil {
		return nil, 0, err
	}

	// This filters without allocating
	// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
	authorizations := as[:0]
	for _, a := range as {
		err := authorizeReadAuthorization(ctx, a.UserID)
		if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized {
			return nil, 0, err
		}

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

		authorizations = append(authorizations, a)
	}

	return authorizations, len(authorizations), nil
}
991044
func (e *Enforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) bool {
	return e.RemoveFilteredNamedPolicy("p", fieldIndex, fieldValues...)
}
978299
func (sc *SimpleCollection) AccessFilter() Filter {
	return func(sd common.SignedData) bool {
		if err := sc.accessPolicy.Evaluate([]*common.SignedData{&sd}); err != nil {
			return false
		}
		return true
	}
}
1324915
func (f *aclFilter) filterPreparedQueries(queries *structs.PreparedQueries) {
	// Management tokens can see everything with no filtering.
	if f.authorizer.ACLWrite() {
		return
	}

	// Otherwise, we need to see what the token has access to.
	ret := make(structs.PreparedQueries, 0, len(*queries))
	for _, query := range *queries {
		// If no prefix ACL applies to this query then filter it, since
		// we know at this point the user doesn't have a management
		// token, otherwise see what the policy says.
		prefix, ok := query.GetACLPrefix()
		if !ok || !f.authorizer.PreparedQueryRead(prefix) {
			f.logger.Printf("[DEBUG] consul: dropping prepared query %q from result due to ACLs", query.ID)
			continue
		}

		// Redact any tokens if necessary. We make a copy of just the
		// pointer so we don't mess with the caller's slice.
		final := query
		f.redactPreparedQueryTokens(&final)
		ret = append(ret, final)
	}
	*queries = ret
}
1062851
func (c *Client) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) ([]*platform.Authorization, int, error) {
	if filter.ID != nil {
		a, err := c.FindAuthorizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &platform.Error{
				Err: err,
				Op:  getOp(platform.OpFindAuthorizations),
			}
		}

		return []*platform.Authorization{a}, 1, nil
	}

	if filter.Token != nil {
		a, err := c.FindAuthorizationByToken(ctx, *filter.Token)
		if err != nil {
			return nil, 0, &platform.Error{
				Err: err,
				Op:  getOp(platform.OpFindAuthorizations),
			}
		}

		return []*platform.Authorization{a}, 1, nil
	}

	as := []*platform.Authorization{}
	err := c.db.View(func(tx *bolt.Tx) error {
		auths, err := c.findAuthorizations(ctx, tx, filter)
		if err != nil {
			return err
		}
		as = auths
		return nil
	})

	if err != nil {
		return nil, 0, &platform.Error{
			Err: err,
			Op:  getOp(platform.OpFindAuthorizations),
		}
	}

	return as, len(as), nil
}
775277
func (m *Manager) GetOrganizationAuthorizations(globalId string) (authorizations []Authorization, err error) {
	qry := bson.M{"grantedto": globalId}
	err = m.getAuthorizationCollection().Find(qry).All(&authorizations)
	if authorizations == nil {
		authorizations = []Authorization{}
	}
	return
}
1031849
func filterHeaders(headers http.Header, iterator headerIterator) {
	for k, v := range headers {
		// Skip sensitive headers
		if k == "Authorization" || k == "Cookie" {
			iterator(k, []string{"*****"})
			continue
		}
		iterator(k, v)
	}
}
1342425
func (c *certPool) filterCerts(certs ...*x509.Certificate) []*x509.Certificate {
	c.lock.RLock()
	defer c.lock.RUnlock()

	filtered := []*x509.Certificate{}

CertLoop:
	for _, cert := range certs {
		if cert == nil {
			continue
		}
		possibilities := c.certsByName[string(cert.RawSubject)]
		for _, p := range possibilities {
			if c.certs[p].Equal(cert) {
				continue CertLoop
			}
		}
		filtered = append(filtered, cert)
	}

	//remove duplicate from list of certs being passed
	return removeDuplicates(filtered...)
}
618279
func (sa *StorageAuthority) GetAuthorizations(ctx context.Context, req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) {
	return &sapb.Authorizations{}, nil
}
1107717
func hasAuthorizedRole(sourceRole, providedRole string) bool {
	switch sourceRole {
	case ViewerRoleName:
		switch providedRole {
		case ViewerRoleName, EditorRoleName, AdminRoleName:
			return true
		}
	case EditorRoleName:
		switch providedRole {
		case EditorRoleName, AdminRoleName:
			return true
		}
	case AdminRoleName:
		switch providedRole {
		case AdminRoleName:
			return true
		}
	}

	return false
}