errors.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package cmd
  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 checkLoginAndRun(ctx context.Context, args []string, runner func(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConfig config.CLIConfig, args []string) error) error {
  19. cliConf, err := config.InitAndLoadConfig()
  20. if err != nil {
  21. return fmt.Errorf("error loading porter config: %w", err)
  22. }
  23. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  24. BaseURL: fmt.Sprintf("%s/api", cliConf.Host),
  25. BearerToken: cliConf.Token,
  26. CookieFileName: "cookie.json",
  27. })
  28. if err != nil {
  29. return fmt.Errorf("error creating porter API client: %w", err)
  30. }
  31. user, err := client.AuthCheck(ctx)
  32. if err != nil {
  33. red := color.New(color.FgRed)
  34. if strings.Contains(err.Error(), "Forbidden") {
  35. red.Print("You are not logged in. Log in using \"porter auth login\"\n")
  36. return ErrNotLoggedIn
  37. } else if strings.Contains(err.Error(), "connection refused") {
  38. red.Printf("Unable to connect to the Porter server at %s\n", cliConf.Host)
  39. red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
  40. red.Print("To start a local server, run \"porter server start\"\n")
  41. return ErrCannotConnect
  42. }
  43. red.Fprintf(os.Stderr, "Error: %v\n", err.Error())
  44. return err
  45. }
  46. err = runner(ctx, user, client, cliConf, args)
  47. if err != nil {
  48. red := color.New(color.FgRed)
  49. if strings.Contains(err.Error(), "403") {
  50. red.Print("You do not have the necessary permissions to view this resource")
  51. return nil
  52. } else if strings.Contains(err.Error(), "connection refused") {
  53. red.Printf("Unable to connect to the Porter server at %s\n", cliConf.Host)
  54. red.Print("To set a different host, run \"porter config set-host [HOST]\"")
  55. red.Print("To start a local server, run \"porter server start\"")
  56. return nil
  57. }
  58. cliErrors.GetErrorHandler(cliConf).HandleError(err)
  59. return err
  60. }
  61. return nil
  62. }