Skip to content

Commit

Permalink
save token expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
aviau committed Sep 13, 2024
1 parent 6c167ce commit 117b616
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
18 changes: 14 additions & 4 deletions api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ import (
"fmt"
"net/http"
"net/url"
"time"
)

type ApiClient struct {
tenantId int
apiKey string
httpClient *http.Client
baseUrl string
tenantId int
apiKey string
httpClient *http.Client
baseUrl string
apiToken string
apiTokenExp time.Time
}

type ApiClientOption func(*ApiClient)
Expand Down Expand Up @@ -94,5 +97,12 @@ func (client *ApiClient) GenerateToken() (string, error) {
return "", err
}

client.apiToken = tokenResponse.Token
client.apiTokenExp = time.Now().Add(time.Minute * 45)

return tokenResponse.Token, nil
}

func (client *ApiClient) isApiTokenExpired() bool {
return client.apiTokenExp.Before(time.Now())
}
5 changes: 5 additions & 0 deletions api_client_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ func TestGenerateToken(t *testing.T) {
)
defer clientTest.Close()

assert.Equal(t, "", clientTest.apiClient.apiToken, "The initial api token should be empty")
assert.True(t, clientTest.apiClient.isApiTokenExpired(), "The initial api token exp should be before now")

token, err := clientTest.apiClient.GenerateToken()
assert.NoError(t, err, "Generating a token")
assert.Equal(t, "test-token-hello", token)
assert.Equal(t, "test-token-hello", clientTest.apiClient.apiToken)
assert.False(t, clientTest.apiClient.isApiTokenExpired(), "The api token should be unexpired")
}

0 comments on commit 117b616

Please sign in to comment.