errors.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package commands
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "github.com/fatih/color"
  9. api "github.com/porter-dev/porter/api/client"
  10. "github.com/porter-dev/porter/api/types"
  11. "github.com/porter-dev/porter/cli/cmd/config"
  12. cliErrors "github.com/porter-dev/porter/cli/cmd/errors"
  13. )
  14. var (
  15. ErrNotLoggedIn error = errors.New("You are not logged in.")
  16. ErrCannotConnect error = errors.New("Unable to connect to the Porter server.")
  17. )
  18. func checkLoginAndRunWithConfig(ctx context.Context, cliConf config.CLIConfig, args []string, runner func(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, args []string) error) error {
  19. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  20. BaseURL: fmt.Sprintf("%s/api", cliConf.Host),
  21. BearerToken: cliConf.Token,
  22. CookieFileName: "cookie.json",
  23. })
  24. if err != nil {
  25. return fmt.Errorf("error creating porter API client: %w", err)
  26. }
  27. user, err := client.AuthCheck(ctx)
  28. if err != nil {
  29. red := color.New(color.FgRed)
  30. if strings.Contains(err.Error(), "Forbidden") {
  31. red.Print("You are not logged in. Log in using \"porter auth login\"\n")
  32. return ErrNotLoggedIn
  33. } else if strings.Contains(err.Error(), "connection refused") {
  34. red.Printf("Unable to connect to the Porter server at %s\n", cliConf.Host)
  35. red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
  36. red.Print("To start a local server, run \"porter server start\"\n")
  37. return ErrCannotConnect
  38. }
  39. red.Fprintf(os.Stderr, "Error: %v\n", err.Error())
  40. return err
  41. }
  42. err = runner(ctx, user, client, cliConf, args)
  43. if err != nil {
  44. red := color.New(color.FgRed)
  45. if strings.Contains(err.Error(), "403") {
  46. red.Print("You do not have the necessary permissions to view this resource")
  47. return nil
  48. } else if strings.Contains(err.Error(), "connection refused") {
  49. red.Printf("Unable to connect to the Porter server at %s\n", cliConf.Host)
  50. red.Print("To set a different host, run \"porter config set-host [HOST]\"")
  51. red.Print("To start a local server, run \"porter server start\"")
  52. return nil
  53. }
  54. cliErrors.GetErrorHandler(cliConf).HandleError(err)
  55. return err
  56. }
  57. return nil
  58. }