(feat/cmd): add default token

pull/10616/head
Kelvin Wang 2018-11-01 22:34:22 -04:00
parent 886aa130ea
commit a783c213c3
2 changed files with 28 additions and 0 deletions

View File

@ -2,8 +2,11 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath"
"github.com/influxdata/platform/internal/fs"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -39,6 +42,26 @@ type Flags struct {
var flags Flags var flags Flags
func defaultTokenPath() string {
dir, err := fs.InfluxDir()
if err != nil {
return ""
}
return filepath.Join(dir, "credentials")
}
func getTokenFromPath(path string) (string, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(b), nil
}
func writeTokenToPath(tok string, path string) error {
return ioutil.WriteFile(path, []byte(tok), 0600)
}
func init() { func init() {
viper.SetEnvPrefix("INFLUX") viper.SetEnvPrefix("INFLUX")
@ -46,6 +69,8 @@ func init() {
viper.BindEnv("TOKEN") viper.BindEnv("TOKEN")
if h := viper.GetString("TOKEN"); h != "" { if h := viper.GetString("TOKEN"); h != "" {
flags.token = h flags.token = h
} else if tok, err := getTokenFromPath(defaultTokenPath()); err == nil {
flags.token = tok
} }
influxCmd.PersistentFlags().StringVar(&flags.host, "host", "http://localhost:9999", "HTTP address of Influx") influxCmd.PersistentFlags().StringVar(&flags.host, "host", "http://localhost:9999", "HTTP address of Influx")

View File

@ -64,6 +64,9 @@ func setupF(cmd *cobra.Command, args []string) {
"Bucket": result.Bucket.Name, "Bucket": result.Bucket.Name,
"Token": result.Auth.Token, "Token": result.Auth.Token,
}) })
writeTokenToPath(result.Auth.Token, defaultTokenPath())
w.Flush() w.Flush()
} }