Skip to content

Commit e07af9f

Browse files
authored
feat: Add method to return token type (#75)
Whilst the token itself now contains the token type, it is useful to be able to determine the type of tokens the token client will return without fetching a token first. An example user of this functionality will be the usage client, which needs to determine if an API call is needed to fetch the team name when the authentication is using an API key. Refs: cloudquery/cloudquery-issues#893
1 parent db26b9c commit e07af9f

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

auth/token.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ func NewTokenClient() *TokenClient {
6666
// GetToken returns the ID token
6767
// If CLOUDQUERY_API_KEY is set, it returns that value, otherwise it returns an ID token generated from the refresh token.
6868
func (tc *TokenClient) GetToken() (Token, error) {
69-
if token := os.Getenv(EnvVarCloudQueryAPIKey); token != "" {
70-
return Token{Type: APIKey, Value: token}, nil
69+
if tc.GetTokenType() == APIKey {
70+
return Token{Type: APIKey, Value: os.Getenv(EnvVarCloudQueryAPIKey)}, nil
7171
}
7272

7373
// If the token is not expired, return it
@@ -98,6 +98,14 @@ func (tc *TokenClient) GetToken() (Token, error) {
9898
return Token{Type: BearerToken, Value: tc.idToken}, nil
9999
}
100100

101+
// GetTokenType returns the type of token that will be returned by GetToken
102+
func (tc *TokenClient) GetTokenType() TokenType {
103+
if token := os.Getenv(EnvVarCloudQueryAPIKey); token != "" {
104+
return APIKey
105+
}
106+
return BearerToken
107+
}
108+
101109
func (tc *TokenClient) generateToken(refreshToken string) (*tokenResponse, error) {
102110
data := url.Values{}
103111
data.Set("grant_type", "refresh_token")

auth/token_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"testing"
1010
"time"
1111

12+
"github.com/stretchr/testify/assert"
1213
"github.com/stretchr/testify/require"
1314
)
1415

@@ -103,6 +104,20 @@ func TestTokenClient_GetToken_LongExpiry(t *testing.T) {
103104
require.Equal(t, Token{Type: BearerToken, Value: "my_id_token_0"}, token, "expected to reuse token")
104105
}
105106

107+
func TestTokenClient_BearerTokenType(t *testing.T) {
108+
tc := NewTokenClient()
109+
110+
assert.Equal(t, BearerToken, tc.GetTokenType())
111+
}
112+
113+
func TestTokenClient_APIKeyTokenType(t *testing.T) {
114+
t.Setenv(EnvVarCloudQueryAPIKey, "my_token")
115+
116+
tc := NewTokenClient()
117+
118+
assert.Equal(t, APIKey, tc.GetTokenType())
119+
}
120+
106121
func overrideEnvironmentVariable(t *testing.T, key, value string) func() {
107122
originalValue := os.Getenv(key)
108123
resetFn := func() {

0 commit comments

Comments
 (0)