2023-01-06 15:15:57 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2023-10-11 11:12:18 +00:00
|
|
|
"errors"
|
2023-01-06 15:15:57 +00:00
|
|
|
"time"
|
|
|
|
|
2023-05-16 16:35:39 +00:00
|
|
|
"github.com/databricks/cli/libs/auth"
|
2023-01-06 15:15:57 +00:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
func newTokenCommand(persistentAuth *auth.PersistentAuth) *cobra.Command {
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "token [HOST]",
|
|
|
|
Short: "Get authentication token",
|
|
|
|
}
|
2023-01-06 15:15:57 +00:00
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
var tokenTimeout time.Duration
|
|
|
|
cmd.Flags().DurationVar(&tokenTimeout, "timeout", auth.DefaultTimeout,
|
|
|
|
"Timeout for acquiring a token.")
|
|
|
|
|
|
|
|
cmd.RunE = func(cmd *cobra.Command, args []string) error {
|
2023-07-12 15:36:09 +00:00
|
|
|
ctx := cmd.Context()
|
2023-10-11 11:12:18 +00:00
|
|
|
|
|
|
|
var profileName string
|
|
|
|
profileFlag := cmd.Flag("profile")
|
|
|
|
if profileFlag != nil {
|
|
|
|
profileName = profileFlag.Value.String()
|
|
|
|
// If a profile is provided we read the host from the .databrickscfg file
|
|
|
|
if profileName != "" && len(args) > 0 {
|
|
|
|
return errors.New("providing both a profile and a host parameters is not supported")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
err := setHost(ctx, profileName, persistentAuth, args)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-01-06 15:15:57 +00:00
|
|
|
}
|
2023-07-12 15:36:09 +00:00
|
|
|
defer persistentAuth.Close()
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, tokenTimeout)
|
2023-01-06 15:15:57 +00:00
|
|
|
defer cancel()
|
2023-07-12 15:36:09 +00:00
|
|
|
t, err := persistentAuth.Load(ctx)
|
2023-01-06 15:15:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
raw, err := json.MarshalIndent(t, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
cmd.OutOrStdout().Write(raw)
|
|
|
|
return nil
|
2023-07-27 10:03:08 +00:00
|
|
|
}
|
2023-01-06 15:15:57 +00:00
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
return cmd
|
2023-01-06 15:15:57 +00:00
|
|
|
}
|