Skip to content

Commit

Permalink
add: detect which authentication type is used
Browse files Browse the repository at this point in the history
People still get confused whether they are using API tokens or an API
key. To reduce the confusion at `add` time, we can infer what type it is
from the value provided.
  • Loading branch information
jacobbednarz committed Sep 17, 2020
1 parent f07f90f commit b2bd432
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"regexp"
"strings"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -43,14 +44,15 @@ var addCmd = &cobra.Command{
emailAddress, _ := reader.ReadString('\n')
emailAddress = strings.TrimSpace(emailAddress)

fmt.Print("Authentication type (api_token or api_key): ")
authType, _ := reader.ReadString('\n')
authType = strings.TrimSpace(authType)

fmt.Print("Authentication value: ")
fmt.Print("Authentication value (API key or API token): ")
authValue, _ := reader.ReadString('\n')
authValue = strings.TrimSpace(authValue)

authType, err := determineAuthType(authValue)
if err != nil {
log.Fatalf("failed to detect authentication type: %s", err)
}

home, err := homedir.Dir()
if err != nil {
log.Fatal("unable to find home directory: ", err)
Expand Down Expand Up @@ -78,3 +80,13 @@ var addCmd = &cobra.Command{
})
},
}

func determineAuthType(s string) (string, error) {
if apiTokenMatch, _ := regexp.MatchString("[A-Za-z0-9-_]{40}", s); apiTokenMatch {
return "api_token", nil
} else if apiKeyMatch, _ := regexp.MatchString("[0-9a-f]{37}", s); apiKeyMatch {
return "api_key", nil
} else {
return "", errors.New("invalid API token or API key format")
}
}

0 comments on commit b2bd432

Please sign in to comment.