github.com/supabase/cli@v1.168.1/internal/utils/tenant/client.go (about)

     1  package tenant
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"time"
     7  
     8  	"github.com/go-errors/errors"
     9  	"github.com/supabase/cli/internal/utils"
    10  	"github.com/supabase/cli/pkg/api"
    11  	"github.com/supabase/cli/pkg/fetcher"
    12  )
    13  
    14  var (
    15  	ErrAuthToken  = errors.New("Authorization failed for the access token and project ref pair")
    16  	errMissingKey = errors.New("Anon key not found.")
    17  )
    18  
    19  type ApiKey struct {
    20  	Anon        string
    21  	ServiceRole string
    22  }
    23  
    24  func (a ApiKey) IsEmpty() bool {
    25  	return len(a.Anon) == 0 && len(a.ServiceRole) == 0
    26  }
    27  
    28  func NewApiKey(resp []api.ApiKeyResponse) ApiKey {
    29  	var result ApiKey
    30  	for _, key := range resp {
    31  		if key.Name == "anon" {
    32  			result.Anon = key.ApiKey
    33  		}
    34  		if key.Name == "service_role" {
    35  			result.ServiceRole = key.ApiKey
    36  		}
    37  	}
    38  	return result
    39  }
    40  
    41  func GetApiKeys(ctx context.Context, projectRef string) (ApiKey, error) {
    42  	resp, err := utils.GetSupabase().GetProjectApiKeysWithResponse(ctx, projectRef)
    43  	if err != nil {
    44  		return ApiKey{}, errors.Errorf("failed to get api keys: %w", err)
    45  	}
    46  	if resp.JSON200 == nil {
    47  		return ApiKey{}, errors.Errorf("%w: %s", ErrAuthToken, string(resp.Body))
    48  	}
    49  	keys := NewApiKey(*resp.JSON200)
    50  	if keys.IsEmpty() {
    51  		return ApiKey{}, errors.New(errMissingKey)
    52  	}
    53  	return keys, nil
    54  }
    55  
    56  type TenantAPI struct {
    57  	*fetcher.Fetcher
    58  }
    59  
    60  func NewTenantAPI(ctx context.Context, projectRef, anonKey string) TenantAPI {
    61  	server := "https://" + utils.GetSupabaseHost(projectRef)
    62  	client := &http.Client{
    63  		Timeout: 10 * time.Second,
    64  	}
    65  	header := func(req *http.Request) {
    66  		req.Header.Add("apikey", anonKey)
    67  	}
    68  	api := TenantAPI{Fetcher: fetcher.NewFetcher(
    69  		server,
    70  		fetcher.WithHTTPClient(client),
    71  		fetcher.WithRequestEditor(header),
    72  		fetcher.WithUserAgent("SupabaseCLI/"+utils.Version),
    73  	)}
    74  	return api
    75  }