Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(context): ask to use HCLOUD_TOKEN when creating new context #582

Merged
merged 1 commit into from
Oct 25, 2023
Merged
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
53 changes: 37 additions & 16 deletions internal/cmd/context/create.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package context

import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"strings"
"syscall"

"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/term"

"github.com/hetznercloud/cli/internal/state"
)
Expand Down Expand Up @@ -40,25 +42,44 @@

context := &state.ConfigContext{Name: name}

for {
fmt.Printf("Token: ")
btoken, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Print("\n")
if err != nil {
return err
}
token := string(bytes.TrimSpace(btoken))
if token == "" {
continue
var token string

envToken := os.Getenv("HCLOUD_TOKEN")
if envToken != "" {
if len(envToken) != 64 {
fmt.Println("Warning: HCLOUD_TOKEN is set, but token is invalid (must be exactly 64 characters long)")
} else {
fmt.Print("The HCLOUD_TOKEN environment variable is set. Do you want to use the token from HCLOUD_TOKEN for the new context? (Y/n): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
if s := strings.ToLower(scanner.Text()); s == "" || s == "y" || s == "yes" {
token = envToken
}
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}

if token == "" {
for {
fmt.Printf("Token: ")
btoken, err := term.ReadPassword(syscall.Stdin)

Check failure on line 64 in internal/cmd/context/create.go

View workflow job for this annotation

GitHub Actions / build

cannot use syscall.Stdin (variable of type syscall.Handle) as int value in argument to term.ReadPassword
fmt.Print("\n")
if err != nil {
return err
}
token = string(bytes.TrimSpace(btoken))
if token == "" {
continue
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}
break
}
context.Token = token
break
}

context.Token = token

cli.Config.Contexts = append(cli.Config.Contexts, context)
cli.Config.ActiveContext = context

Expand Down
Loading