Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions commands/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
29 changes: 29 additions & 0 deletions commands/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}()

Expand All @@ -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)
}()

Expand Down