1package hooks
2
3import (
4	"fmt"
5	"os"
6
7	"github.com/sensu/sensu-go/cli"
8	"github.com/spf13/cobra"
9)
10
11const (
12	// ConfigurationRequirement used to identify the annotation flag for this handler
13	//
14	// Usage:
15	//
16	//	my_cmd := cobra.Command{
17	//		Use: "Setup",
18	//		Annotations: map[string]string{
19	//			ConfigurationRequirement: ConfigurationNotRequired,
20	//		}
21	//	}
22	ConfigurationRequirement = "CREDENTIALS_REQUIREMENT"
23
24	// ConfigurationNotRequired specifies that the command does not require
25	// credentials to be configured to complete operations
26	ConfigurationNotRequired = "NO"
27)
28
29// ConfigurationPresent - unless the given command specifies that configuration
30// is not required, func checks that host & access-token have been configured.
31func ConfigurationPresent(cmd *cobra.Command, cli *cli.SensuCli) error {
32	// If the command was configured to ignore whether or not the CLI has been
33	// configured stop execution.
34	if cmd.Annotations[ConfigurationRequirement] == ConfigurationNotRequired {
35		return nil
36	}
37
38	// Check that both a URL and an access token are present
39	tokens := cli.Config.Tokens()
40
41	if cli.Config.APIUrl() == "" {
42		return fmt.Errorf(
43			"No API URL is defined. You can configure an API URL by running \"%s configure\"",
44			os.Args[0],
45		)
46	}
47
48	if tokens == nil || tokens.Access == "" {
49		return fmt.Errorf(
50			"Unable to locate credentials. You can configure credentials by running \"%s configure\"",
51			os.Args[0],
52		)
53	}
54
55	return nil
56}
57