// FindAuthorizations retrives all authorizations that match an arbitrary authorization filter.
// Filters using ID, or Token should be efficient.
// Other filters will do a linear scan across all authorizations searching for a match.
423591
func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.AuthorizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Authorization, int, error) {
	if filter.ID != nil {
		a, err := s.FindAuthorizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

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

	if filter.Token != nil {
		a, err := s.FindAuthorizationByToken(ctx, *filter.Token)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

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

	as := []*influxdb.Authorization{}
	err := s.kv.View(ctx, func(tx Tx) error {
		auths, err := s.findAuthorizations(ctx, tx, filter)
		if err != nil {
			return err
		}
		as = auths
		return nil
	})

	if err != nil {
		return nil, 0, &influxdb.Error{
			Err: err,
		}
	}

	return as, len(as), nil
}
792388
func AuthorizationURITenantID(url *url.URL) (string, error) {
	path := strings.TrimPrefix(url.Path, "/")
	if _, err := utils.UUIDFromString(path); err != nil {
		return "", errors.NotValidf("authorization_uri %q", url)
	}
	return path, nil
}
848397
func (c *Client) GetAccounts(accessToken string) (resp GetAccountsResponse, err error) {
	options := GetAccountsOptions{
		AccountIDs: []string{},
	}
	return c.GetAccountsWithOptions(accessToken, options)
}
414949
func (s *BucketService) FindBuckets(ctx context.Context, filter influxdb.BucketFilter, opt ...influxdb.FindOptions) ([]*influxdb.Bucket, int, error) {
	span, ctx := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	// TODO: we'll likely want to push this operation into the database eventually since fetching the whole list of data
	// will likely be expensive.
	bs, _, err := s.s.FindBuckets(ctx, filter, opt...)
	if err != nil {
		return nil, 0, err
	}

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

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

		buckets = append(buckets, b)
	}

	return buckets, len(buckets), nil
}
560722
func (a *AuthorizationsService) All() (auths []Authorization, result *Result) {
	result = a.client.get(a.URL, &auths)
	return
}
897486
func (s *OrgService) FindOrganization(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) {
	o, err := s.s.FindOrganization(ctx, filter)
	if err != nil {
		return nil, err
	}

	if err := authorizeReadOrg(ctx, o.ID); err != nil {
		return nil, err
	}

	return o, nil
}
735241
func (client *Client) GetSecurityGroups(filters ...Filter) ([]SecurityGroup, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetSecurityGroupsRequest,
		Query:       ConvertFilterParameters(filters),
	})

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

	var securityGroupsList []SecurityGroup
	warnings, err := client.paginate(request, SecurityGroup{}, func(item interface{}) error {
		if securityGroup, ok := item.(SecurityGroup); ok {
			securityGroupsList = append(securityGroupsList, securityGroup)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   SecurityGroup{},
				Unexpected: item,
			}
		}
		return nil
	})

	return securityGroupsList, warnings, err
}
989758
func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) {
	a, err := s.s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return nil, err
	}

	if err := authorizeReadAuthorization(ctx, a.UserID); err != nil {
		return nil, err
	}

	return a, nil
}
1238983
func (s *Service) FindOrganizations(ctx context.Context, filter influxdb.OrganizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Organization, int, error) {
	if filter.ID != nil {
		o, err := s.FindOrganizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

		return []*influxdb.Organization{o}, 1, nil
	}

	if filter.Name != nil {
		o, err := s.FindOrganizationByName(ctx, *filter.Name)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

		return []*influxdb.Organization{o}, 1, nil
	}

	os := []*influxdb.Organization{}
	filterFn := filterOrganizationsFn(filter)
	err := s.kv.View(ctx, func(tx Tx) error {
		return forEachOrganization(ctx, tx, func(o *influxdb.Organization) bool {
			if filterFn(o) {
				os = append(os, o)
			}
			return true
		})
	})

	if err != nil {
		return nil, 0, &influxdb.Error{
			Err: err,
		}
	}

	return os, len(os), nil
}
1304528
func (ssa *SQLStorageAuthority) GetValidAuthorizations(
	ctx context.Context,
	registrationID int64,
	names []string,
	now time.Time) (map[string]*core.Authorization, error) {
	return ssa.getAuthorizations(
		ctx,
		authorizationTable,
		string(core.StatusValid),
		registrationID,
		names,
		now,
		false)
}
386145
func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error {
	return s.DeleteAuthorizationFn(ctx, id)
}
422859
func (s *Service) FindOrganizations(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error) {
	op := OpPrefix + platform.OpFindOrganizations
	if filter.ID != nil {
		o, err := s.FindOrganizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &platform.Error{
				Op:  op,
				Err: err,
			}
		}

		return []*platform.Organization{o}, 1, nil
	}

	filterFunc := func(o *platform.Organization) bool { return true }
	if filter.Name != nil {
		filterFunc = func(o *platform.Organization) bool {
			return o.Name == *filter.Name
		}
	}

	orgs, pe := s.filterOrganizations(ctx, filterFunc)
	if pe != nil {
		return nil, 0, &platform.Error{
			Err: pe,
			Op:  op,
		}
	}

	if len(orgs) == 0 {
		return orgs, 0, &platform.Error{
			Code: platform.ENotFound,
			Op:   op,
			Msg:  errOrganizationNotFound,
		}
	}

	return orgs, len(orgs), nil
}
1246233
func (m *GormIdentityRoleRepository) FindPermissions(ctx context.Context, identityID uuid.UUID, resourceID string, scopeName string) ([]IdentityRole, error) {
	var results []IdentityRole
	err := m.db.Table(m.TableName()).Where(`deleted_at IS NULL AND identity_id IN (
  SELECT
    id
  FROM
    identities i
  WHERE
    id = ? /* IDENTITY_ID */
    OR id IN (
    WITH RECURSIVE m AS (
      SELECT 
        member_of 
      FROM 
        membership 
      WHERE 
        member_id = ? /* IDENTITY_ID */
      UNION SELECT 
        p.member_of 
      FROM 
        membership p INNER JOIN m ON m.member_of = p.member_id
    ) 
    SELECT member_of FROM m
    )
  )
  AND resource_id IN (
  WITH RECURSIVE m AS (
  SELECT
    resource_id, parent_resource_id
  FROM
    resource
  WHERE
    deleted_at IS NULL
    AND resource_id = ? /* RESOURCE_ID */
  UNION SELECT
    p.resource_id, p.parent_resource_id
  FROM
    resource p INNER JOIN m ON m.parent_resource_id = p.resource_id
  )
  SELECT
    m.resource_id
  FROM
    m
  )
  AND (role_id IN (
    SELECT
      r.role_id
    FROM
      resource res,
      role r,
      role_scope rs,
      resource_type_scope rts
    WHERE
      res.resource_id = ? /* RESOURCE_ID */
      AND res.deleted_at IS NULL
      AND res.resource_type_id = r.resource_type_id
      AND r.deleted_at IS NULL
      AND r.role_id = rs.role_id
      AND rs.scope_id = rts.resource_type_scope_id
      AND rs.deleted_at IS NULL
      AND rts.name = ? /* SCOPE */
      AND rts.deleted_at IS NULL
  ) OR role_id IN (
    SELECT DISTINCT
      rl.role_id
    FROM
      (
    WITH RECURSIVE prm AS (
    SELECT
      rm.from_role_id,
      rm.to_role_id
    FROM
      role_mapping rm,
      role r,
      role_scope rs,
      resource_type_scope rts
    WHERE
      rm.deleted_at IS NULL
      AND rm.to_role_id = r.role_id
      AND r.deleted_at IS NULL
      AND r.role_id = rs.role_id
      AND rs.deleted_at IS NULL
      AND rs.scope_id = rts.resource_type_scope_id
      AND rts.deleted_at IS NULL
      AND rts.name = ? /* SCOPE */
      AND rm.resource_id IN (WITH RECURSIVE m AS ( /* only resources that are in the ancestor hierarchy */
      SELECT
        resource_id, parent_resource_id
      FROM
        resource
      WHERE
        resource_id = ? /* RESOURCE_ID */
        AND deleted_at IS NULL
      UNION SELECT
        p.resource_id, p.parent_resource_id
      FROM
        resource p INNER JOIN m ON m.parent_resource_id = p.resource_id
      )
      SELECT
        m.resource_id
      FROM
        m)
    UNION SELECT
     trm.from_role_id,
     trm.to_role_id
    FROM
      role_mapping trm INNER JOIN prm ON prm.from_role_id = trm.to_role_id
    WHERE
      trm.deleted_at IS NULL
      AND trm.resource_id IN (WITH RECURSIVE m AS ( /* only resources that are in this role mapping's ancestor hierarchy */
      SELECT
        resource_id, parent_resource_id
      FROM
        resource
      WHERE 
        resource_id = trm.resource_id
        AND deleted_at IS NULL
      UNION SELECT
        p.resource_id, p.parent_resource_id
      FROM
        resource p INNER JOIN m ON m.parent_resource_id = p.resource_id
      )
      SELECT 
        m.resource_id
      FROM
        m)
      )
    SELECT 
      prm.from_role_id,
      prm.to_role_id
    FROM
      prm) AS mappings
    CROSS JOIN LATERAL (
      VALUES (from_role_id), (to_role_id)
      ) AS rl (role_id))
  )`, identityID, identityID, resourceID, resourceID, scopeName, scopeName, resourceID).Scan(&results).Error

	if err != nil {
		return nil, errs.WithStack(err)
	}

	return results, nil
}
773326
func TokenAuthorizedWhere(a *Authorization) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	// TODO(desa): what to do about retrieving all documents using auth? (e.g. write/read:documents/*)
	var ids []ID
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		if !a.IsActive() {
			return nil, &Error{
				Code: EUnauthorized,
				Msg:  "authorizer cannot access documents",
			}
		}

		for _, p := range a.Permissions {
			if p.Resource.Type == DocumentsResourceType && p.Resource.OrgID != nil {
				oids, err := idx.GetAccessorsDocuments("org", *p.Resource.OrgID)
				if err != nil {
					return nil, err
				}
				ids = append(ids, oids...)
			}

			if p.Resource.Type == DocumentsResourceType && p.Resource.ID != nil {
				ids = append(ids, *p.Resource.ID)
			}
		}

		return ids, nil
	}
}
1100935
func (c *UserConfig) GetAuthorizeURL(service *Service) (string, error) {
	if c.RequestTokenKey == "" || c.RequestTokenSecret == "" {
		return "", fmt.Errorf("No configured request token")
	}
	token := url.QueryEscape(c.RequestTokenKey)
	return service.AuthorizeURL + "?oauth_token=" + token, nil
}
484842
func (c *Client) FindAuthorizationByID(ctx context.Context, id platform.ID) (*platform.Authorization, error) {
	var a *platform.Authorization
	var err error
	err = c.db.View(func(tx *bolt.Tx) error {
		var pe *platform.Error
		a, pe = c.findAuthorizationByID(ctx, tx, id)
		if pe != nil {
			pe.Op = getOp(platform.OpFindAuthorizationByID)
			err = pe
		}
		return err
	})

	return a, err
}
85651
func (s *OrganizationService) FindOrganizations(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error) {
	url, err := newURL(s.Addr, organizationPath)
	if err != nil {
		return nil, 0, err
	}
	qp := url.Query()

	if filter.Name != nil {
		qp.Add("name", *filter.Name)
	}
	if filter.ID != nil {
		qp.Add("id", filter.ID.String())
	}
	url.RawQuery = qp.Encode()

	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return nil, 0, err
	}

	SetToken(s.Token, req)
	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, 0, err
	}

	if err := CheckError(resp, true); err != nil {
		return nil, 0, err
	}

	var os orgsResponse
	if err := json.NewDecoder(resp.Body).Decode(&os); err != nil {
		return nil, 0, err
	}

	orgs := os.ToPlatform()
	return orgs, len(orgs), nil

}