diff --git a/commands/auth.go b/commands/auth.go index fa2d3cd70..120605c5c 100644 --- a/commands/auth.go +++ b/commands/auth.go @@ -158,20 +158,23 @@ To create new contexts, see the help for `+"`"+`doctl auth init`+"`"+`.`, Writer // XDG_CONFIG_HOME is not set, use $HOME/.config. On Windows use %APPDATA%/doctl/config. func RunAuthInit(retrieveUserTokenFunc func() (string, error)) func(c *CmdConfig) error { return func(c *CmdConfig) error { - token := c.getContextAccessToken() context := strings.ToLower(Context) if context == "" { context = strings.ToLower(viper.GetString("context")) } - if token == "" { + var token string + if Token != "" { + // Use the token provided via --access-token flag. + token = Token + } else { + // Always prompt for a new token, even if one exists in the config. + // This ensures the user can replace an expired or revoked token. in, err := retrieveUserTokenFunc() if err != nil { return fmt.Errorf("Unable to read DigitalOcean access token: %s", err) } token = strings.TrimSpace(in) - } else { - template.Render(c.Out, `Using token for context {{highlight .}}{{nl}}`, context) } c.setContextAccessToken(token) diff --git a/commands/auth_test.go b/commands/auth_test.go index 72c5d457b..e63ff8024 100644 --- a/commands/auth_test.go +++ b/commands/auth_test.go @@ -103,9 +103,12 @@ func TestAuthInitConfig(t *testing.T) { func TestAuthInitWithProvidedToken(t *testing.T) { cfw := cfgFileWriter + origToken := Token + Token = "valid-token" viper.Set(doctl.ArgAccessToken, "valid-token") defer func() { cfgFileWriter = cfw + Token = origToken viper.Set(doctl.ArgAccessToken, nil) }() @@ -123,11 +126,37 @@ func TestAuthInitWithProvidedToken(t *testing.T) { }) } +func TestAuthInitPromptsWhenTokenExists(t *testing.T) { + cfw := cfgFileWriter + // Simulate an existing (possibly expired) token in the config. + viper.Set(doctl.ArgAccessToken, "expired-token") + defer func() { + cfgFileWriter = cfw + viper.Set(doctl.ArgAccessToken, nil) + }() + + retrieveUserTokenFunc := func() (string, error) { + return "new-valid-token", nil + } + + cfgFileWriter = func() (io.WriteCloser, error) { return &nopWriteCloser{Writer: io.Discard}, nil } + + withTestClient(t, func(config *CmdConfig, tm *tcMocks) { + tm.oauth.EXPECT().TokenInfo(gomock.Any()).Return(&do.OAuthTokenInfo{}, nil) + + err := RunAuthInit(retrieveUserTokenFunc)(config) + assert.NoError(t, err) + }) +} + func TestAuthForcesLowercase(t *testing.T) { cfw := cfgFileWriter + origToken := Token + Token = "valid-token" viper.Set(doctl.ArgAccessToken, "valid-token") defer func() { cfgFileWriter = cfw + Token = origToken viper.Set(doctl.ArgAccessToken, nil) }()