From 4d489f16868093dea5fcf5c61ceb76b13caae351 Mon Sep 17 00:00:00 2001 From: surdeus Date: Sat, 27 Jan 2024 09:21:02 +0300 Subject: [PATCH] feat: autorefreshing after the access token expires. --- api/api.go | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index 1dcad28..e521b4d 100644 --- a/api/api.go +++ b/api/api.go @@ -29,7 +29,7 @@ type ClientOptions struct { ClientSecret string `json:"client_secret"` AccessToken string `json:"access_token"` - ExpirationDate time.Time `json:"access"` + ExpirationAt time.Time `json:"expiration_at"` RefreshToken string `json:"refresh_token"` } @@ -265,6 +265,10 @@ func (api *Client) ExchangeAuth() (*TokenPair, error) { api.options.AccessToken = result.AccessToken api.options.RefreshToken = result.RefreshToken + now := time.Now() + api.options.ExpirationAt = now.Add( + time.Second*time.Duration(result.ExpiresIn), + ) err = api.writeSecret() if err != nil { return nil, err @@ -272,6 +276,17 @@ func (api *Client) ExchangeAuth() (*TokenPair, error) { return ret, nil } +func (api *Client) RefreshTokenIfExpired() error { + now := time.Now() + if now.After(api.options.ExpirationAt.Add(-time.Second*2)) { + _, err := api.RefreshToken() + if err != nil { + return err + } + } + return nil +} + func (api *Client) RefreshToken() (*OauthTokenResponse, error) { result := new(OauthTokenResponse) request := map[string]string{ @@ -293,6 +308,10 @@ func (api *Client) RefreshToken() (*OauthTokenResponse, error) { api.options.AccessToken = result.AccessToken api.options.RefreshToken = result.RefreshToken + now := time.Now() + api.options.ExpirationAt = now.Add( + time.Second*time.Duration(result.ExpiresIn), + ) err = api.writeSecret() if err != nil { return nil, err @@ -306,6 +325,10 @@ func (api *Client) Get(resource string, result interface{}, abs ...bool) error { if len(abs) > 0 { a = abs[0] } + err := api.RefreshTokenIfExpired() + if err != nil { + return err + } return api.doRequest(resource, requestOptions{ HttpMethod: http.MethodGet, Body: nil, @@ -315,6 +338,10 @@ func (api *Client) Get(resource string, result interface{}, abs ...bool) error { } func (api *Client) Post(resource string, request interface{}, result interface{}) error { + err := api.RefreshTokenIfExpired() + if err != nil { + return err + } return api.doRequest(resource, requestOptions{ HttpMethod: http.MethodPost, Body: request, @@ -323,6 +350,10 @@ func (api *Client) Post(resource string, request interface{}, result interface{} } func (api *Client) Patch(resource string, request interface{}, result interface{}) error { + err := api.RefreshTokenIfExpired() + if err != nil { + return err + } return api.doRequest(resource, requestOptions{ HttpMethod: http.MethodPatch, Body: request,