2
0

errors.go 1.8 KB

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