Skip to content

Commit

Permalink
refactor(cli): improve readability of CLI authentication check
Browse files Browse the repository at this point in the history
  • Loading branch information
jfeodor committed May 7, 2024
1 parent b503e9b commit aeea5f1
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions cli/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ const (
shootingStarEmoji = "\U0001F320"
)

var ErrNotAuthorized = errors.New("not authorized")

var (
logLevel logging.Level = logging.LevelError
rootCmd = &cobra.Command{
Expand All @@ -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
Expand Down

0 comments on commit aeea5f1

Please sign in to comment.