Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
Expand All @@ -10,6 +11,7 @@ import (
api "github.com/urlscan/urlscan-cli/api"
"github.com/urlscan/urlscan-cli/cmd/pro"
"github.com/urlscan/urlscan-cli/cmd/scan"
"github.com/urlscan/urlscan-cli/pkg/utils"
)

func addHostFlag(flags *pflag.FlagSet) {
Expand All @@ -31,6 +33,7 @@ var RootCmd = &cobra.Command{
Short: "A CLI tool for interacting with urlscan.io",
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// bind flags
if err := viper.BindPFlags(cmd.PersistentFlags()); err != nil {
return err
}
Expand All @@ -45,6 +48,13 @@ var RootCmd = &cobra.Command{
if proxy != "" {
os.Setenv("http_proxy", proxy) //nolint:errcheck
}

// check API key presence
key, err := utils.GetKey()
if err != nil || key == "" {
return fmt.Errorf("API key not found, please set the URLSCAN_API_KEY environment variable or set it in keyring by `urlscan key set`")
}

return nil
},
}
Expand Down
12 changes: 10 additions & 2 deletions pkg/utils/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,26 @@ type APIClient struct {
*api.Client
}

func NewAPIClient() (*APIClient, error) {
func GetKey() (string, error) {
// api key loading precedence:
// 1. Environment variable (URLSCAN_API_KEY)
// 2. Keyring
key := os.Getenv("URLSCAN_API_KEY")
if key == "" {
got, err := NewKeyManager().GetKey()
if err != nil {
return nil, err
return "", err
}
key = got
}
return key, nil
}

func NewAPIClient() (*APIClient, error) {
key, err := GetKey()
if err != nil {
return nil, err
}

c := api.NewClient(key)
c.Agent = fmt.Sprintf("urlscan-cli %s", version.Version)
Expand Down