errors.go 1.8 KB

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