From 117b616ac929a9735417bfcd5b3b29adc51b2144 Mon Sep 17 00:00:00 2001 From: aviau Date: Fri, 13 Sep 2024 17:49:24 -0400 Subject: [PATCH] save token expiration --- api_client.go | 18 ++++++++++++++---- api_client_http_test.go | 5 +++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/api_client.go b/api_client.go index 074a068..9968504 100644 --- a/api_client.go +++ b/api_client.go @@ -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) @@ -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()) +} diff --git a/api_client_http_test.go b/api_client_http_test.go index 5d7b6e8..61a6b4b 100644 --- a/api_client_http_test.go +++ b/api_client_http_test.go @@ -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") }