diff --git a/command/auth.go b/command/auth.go index 6327e10e2f..50431460d5 100644 --- a/command/auth.go +++ b/command/auth.go @@ -153,6 +153,13 @@ func (c *AuthCommand) Run(args []string) int { return 1 } + // Cache the previous token so that it can be restored if authentication fails + var previousToken string + if previousToken, err = tokenHelper.Get(); err != nil { + c.Ui.Error(fmt.Sprintf("Error caching the previous token: %s\n\n", err)) + return 1 + } + // Store the token! if err := tokenHelper.Store(token); err != nil { c.Ui.Error(fmt.Sprintf( @@ -163,14 +170,6 @@ func (c *AuthCommand) Run(args []string) int { return 1 } - // Build the client again so it can read the token we just wrote - client, err = c.Client() - if err != nil { - c.Ui.Error(fmt.Sprintf( - "Error initializing client to verify the token: %s", err)) - return 1 - } - if noVerify { c.Ui.Output(fmt.Sprintf( "Authenticated - no token verification has been performed.", @@ -179,15 +178,41 @@ func (c *AuthCommand) Run(args []string) int { return 0 } + // Build the client again so it can read the token we just wrote + client, err = c.Client() + if err != nil { + c.Ui.Error(fmt.Sprintf( + "Error initializing client to verify the token: %s", err)) + if err := tokenHelper.Store(previousToken); err != nil { + c.Ui.Error(fmt.Sprintf( + "Error restoring the previous token: %s\n\n"+ + "Please reauthenticate with a valid token.", + err)) + } + return 1 + } + // Verify the token secret, err := client.Auth().Token().LookupSelf() if err != nil { c.Ui.Error(fmt.Sprintf( "Error validating token: %s", err)) + if err := tokenHelper.Store(previousToken); err != nil { + c.Ui.Error(fmt.Sprintf( + "Error restoring the previous token: %s\n\n"+ + "Please reauthenticate with a valid token.", + err)) + } return 1 } if secret == nil { c.Ui.Error(fmt.Sprintf("Error: Invalid token")) + if err := tokenHelper.Store(previousToken); err != nil { + c.Ui.Error(fmt.Sprintf( + "Error restoring the previous token: %s\n\n"+ + "Please reauthenticate with a valid token.", + err)) + } return 1 } @@ -211,6 +236,7 @@ func (c *AuthCommand) Run(args []string) int { c.Ui.Output(output) return 0 + } func (c *AuthCommand) listMethods() int {