feat: add username and password login (#418)
* feat: add username and password login * fix: make sure cookie is not empty * chore: go mod tidy * fix: prevent local config from influencing tests * fix: small cleanup on error handling * fix: remove unnecessary trim
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@ -47,6 +48,18 @@ func (c Client) Create(cfg config.Config) error {
|
||||
return c.printConfigs(configPrintOpts{config: &cfg})
|
||||
}
|
||||
|
||||
func (c Client) CreateWithUserPass(cfg config.Config, userPass string) error {
|
||||
if userPass != "" && cfg.Token != "" {
|
||||
return fmt.Errorf("token and username-password cannot be specified together, please choose just one")
|
||||
}
|
||||
|
||||
if cfg.Token == "" && userPass != "" {
|
||||
cfg.Cookie = base64.StdEncoding.EncodeToString([]byte(userPass))
|
||||
}
|
||||
|
||||
return c.Create(cfg)
|
||||
}
|
||||
|
||||
func (c Client) Delete(names []string) error {
|
||||
deleted := make(config.Configs)
|
||||
for _, name := range names {
|
||||
|
56
clients/signin/signin.go
Normal file
56
clients/signin/signin.go
Normal file
@ -0,0 +1,56 @@
|
||||
package signin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/influxdata/influx-cli/v2/api"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func GetCookie(ctx context.Context, params api.ConfigParams, userPass string) (string, error) {
|
||||
bufUserPass, err := base64.StdEncoding.DecodeString(userPass)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
splitUserPass := strings.Split(string(bufUserPass), ":")
|
||||
if len(splitUserPass) < 1 {
|
||||
return "", fmt.Errorf("bad config")
|
||||
}
|
||||
username := splitUserPass[0]
|
||||
var password string
|
||||
if len(splitUserPass) != 2 {
|
||||
fmt.Print("Please provide your password: ")
|
||||
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
password = string(bytePassword)
|
||||
fmt.Println()
|
||||
} else {
|
||||
password = splitUserPass[1]
|
||||
}
|
||||
|
||||
cfg := api.NewAPIConfig(params)
|
||||
client := api.NewAPIClient(cfg)
|
||||
ctx = context.WithValue(ctx, api.ContextBasicAuth, api.BasicAuth{
|
||||
UserName: username,
|
||||
Password: password,
|
||||
})
|
||||
res, err := client.SigninApi.PostSignin(ctx).ExecuteWithHttpInfo()
|
||||
if err != nil {
|
||||
emsg := fmt.Errorf("error signing in, verify signin was not called against cloud influxdb: %w", err)
|
||||
return "", emsg
|
||||
}
|
||||
|
||||
cookies := res.Cookies()
|
||||
if len(cookies) != 1 {
|
||||
return "", fmt.Errorf("failure getting session cookie, multiple cookies")
|
||||
}
|
||||
|
||||
return cookies[0].Value, nil
|
||||
}
|
Reference in New Issue
Block a user