From aeea5f1f09c19ff86568ff5fe77d9197661a00f5 Mon Sep 17 00:00:00 2001 From: Jens Feodor Nielsen Date: Tue, 7 May 2024 11:40:15 +0200 Subject: [PATCH] refactor(cli): improve readability of CLI authentication check --- cli/cmd/root.go | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/cli/cmd/root.go b/cli/cmd/root.go index 0c8a40d9..6df20c61 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -36,6 +36,8 @@ const ( shootingStarEmoji = "\U0001F320" ) +var ErrNotAuthorized = errors.New("not authorized") + var ( logLevel logging.Level = logging.LevelError rootCmd = &cobra.Command{ @@ -57,22 +59,25 @@ var ( "", SilenceUsage: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - if commandRequiresAuthentication(cmd.CommandPath()) { - user := auth.NumerousTenantAuthenticator.GetLoggedInUserFromKeyring() - if user.CheckAuthenticationStatus() == auth.ErrUserNotLoggedIn { - if runtime.GOOS == "windows" { - fmt.Printf("\"%s\" can only be used when logged in.\n", cmd.CommandPath()) - fmt.Println("Use \"numerous login\" to enable this command.") - } else { - fmt.Printf("The use of %s%s%s command can only be done when logged in %s\n", cyanBold, cmd.CommandPath(), resetPrompt, raiseHandEmoji) - fmt.Printf("To enable it, please first proceed with %snumerous login%s %s\n", cyanBold, resetPrompt, shootingStarEmoji) - } - - return errors.New("not authorized") - } - if err := login.RefreshAccessToken(user, http.DefaultClient, auth.NumerousTenantAuthenticator); err != nil { - return err + if !commandRequiresAuthentication(cmd.CommandPath()) { + return nil + } + + user := auth.NumerousTenantAuthenticator.GetLoggedInUserFromKeyring() + if user.CheckAuthenticationStatus() == auth.ErrUserNotLoggedIn { + if runtime.GOOS == "windows" { + fmt.Printf("\"%s\" can only be used when logged in.\n", cmd.CommandPath()) + fmt.Println("Use \"numerous login\" to enable this command.") + } else { + fmt.Printf("The use of %s%s%s command can only be done when logged in %s\n", cyanBold, cmd.CommandPath(), resetPrompt, raiseHandEmoji) + fmt.Printf("To enable it, please first proceed with %snumerous login%s %s\n", cyanBold, resetPrompt, shootingStarEmoji) } + + return ErrNotAuthorized + } + + if err := login.RefreshAccessToken(user, http.DefaultClient, auth.NumerousTenantAuthenticator); err != nil { + return err } return nil