From c455ed95ca41afe75bbbe42f3d9c0c36cfab9cb3 Mon Sep 17 00:00:00 2001 From: Harshit Saini Date: Fri, 3 Jan 2025 17:05:00 +0530 Subject: [PATCH] make it more robust, readable, and aligned with best practices --- cmd/auth.go | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/cmd/auth.go b/cmd/auth.go index 7182d0c..94c5c16 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -13,21 +13,45 @@ import ( // authCmd represents the auth command var authCmd = &cobra.Command{ Use: "auth", - Short: "Please authenticate uthoctl for use with your Utho account. You can generate a token in the control panel at https://console.utho.com/api", - Run: func(cmd *cobra.Command, args []string) { - var token string - for { - fmt.Fprint(os.Stderr, "Enter your api token: ") - b, _ := term.ReadPassword(int(syscall.Stdin)) - token = string(b) - if token != "" { - break - } - } - helper.SaveToken(token) + Short: "Authenticate uthoctl with your Utho account. Generate a token at https://console.utho.com/api", + Long: `The "auth" command allows you to authenticate the uthoctl CLI with your Utho account. +You can generate an API token from the control panel at https://console.utho.com/api.`, + RunE: func(cmd *cobra.Command, args []string) error { + return authenticate() }, } func init() { rootCmd.AddCommand(authCmd) } + +// authenticate handles the authentication process +func authenticate() error { + fmt.Fprintln(os.Stderr, "Please authenticate uthoctl for use with your Utho account.") + + var token string + for { + fmt.Fprint(os.Stderr, "Enter your API token: ") + b, err := term.ReadPassword(int(syscall.Stdin)) + if err != nil { + return fmt.Errorf("failed to read password: %w", err) + } + + token = string(b) + if token == "" { + fmt.Fprintln(os.Stderr, "\nToken cannot be empty. Please try again.") + continue + } + + fmt.Fprintln(os.Stderr) // Ensure proper formatting after input + break + } + + // Save the token using the helper function + if err := helper.SaveToken(token); err != nil { + return fmt.Errorf("failed to save token: %w", err) + } + + fmt.Fprintln(os.Stderr, "Token saved successfully!") + return nil +}