From 7d19c5d251c20852ac123930c3ae56602f882c1f Mon Sep 17 00:00:00 2001 From: virtualzone <13085858+virtualzone@users.noreply.github.com> Date: Mon, 9 Aug 2021 20:20:29 +0200 Subject: [PATCH] Optimized token renewal --- main.go | 10 ++++++---- sdk/login.go | 6 ++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index bbfe2dd..d7ddd05 100644 --- a/main.go +++ b/main.go @@ -86,10 +86,12 @@ func main() { logError("Could not read secret store: " + err.Error()) return } - logVerbose("Renewing access token...") - if _, err := client.RenewAccessToken(); err != nil { - logError("Could not renew access token: " + err.Error()) - return + if client.ShouldRenewAccessToken() { + logVerbose("Renewing access token...") + if _, err := client.RenewAccessToken(); err != nil { + logError("Could not renew access token: " + err.Error()) + return + } } } cmdDef.Fn(client, args) diff --git a/sdk/login.go b/sdk/login.go index 3bc3c8f..857735d 100644 --- a/sdk/login.go +++ b/sdk/login.go @@ -93,6 +93,12 @@ func (client *Client) redeemCodeForAccessToken(code string) (*LoginRedeemCodeRes return &json, nil } +func (client *Client) ShouldRenewAccessToken() bool { + now := time.Now() + diff := now.Sub(client.SecretStore.Expiry) + return diff.Minutes() > -30 +} + func (client *Client) RenewAccessToken() (*LoginRedeemCodeResponse, error) { params := make(HTTPRequestParams) params["client_id"] = client.Config.ClientID