errors.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. )
  12. var ErrNotLoggedIn error = errors.New("You are not logged in.")
  13. var ErrCannotConnect error = errors.New("Unable to connect to the Porter server.")
  14. func checkLoginAndRun(args []string, runner func(user *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error) error {
  15. client := config.GetAPIClient()
  16. user, err := client.AuthCheck(context.Background())
  17. if err != nil {
  18. red := color.New(color.FgRed)
  19. if strings.Contains(err.Error(), "Forbidden") {
  20. red.Print("You are not logged in. Log in using \"porter auth login\"\n")
  21. return ErrNotLoggedIn
  22. } else if strings.Contains(err.Error(), "connection refused") {
  23. red.Printf("Unable to connect to the Porter server at %s\n", cliConf.Host)
  24. red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
  25. red.Print("To start a local server, run \"porter server start\"\n")
  26. return ErrCannotConnect
  27. }
  28. red.Fprintf(os.Stderr, "Error: %v\n", err.Error())
  29. return err
  30. }
  31. err = runner(user, client, args)
  32. if err != nil {
  33. red := color.New(color.FgRed)
  34. if strings.Contains(err.Error(), "403") {
  35. red.Print("You do not have the necessary permissions to view this resource")
  36. return nil
  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]\"")
  40. red.Print("To start a local server, run \"porter server start\"")
  41. return nil
  42. }
  43. red.Fprintf(os.Stderr, "Error: %v\n", err.Error())
  44. return err
  45. }
  46. return nil
  47. }