[core] Re-check token validity more often than on expiry

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2022-03-20 14:32:11 +01:00
parent 2c9a0adfa0
commit 464212c757
Signed by: luzifer
GPG key ID: 0066F03ED215AD7D

View file

@ -23,6 +23,8 @@ import (
const ( const (
timeDay = 24 * time.Hour timeDay = 24 * time.Hour
tokenValidityRecheckInterval = time.Hour
twitchMinCacheTime = time.Second * 30 twitchMinCacheTime = time.Second * 30
twitchRequestRetries = 5 twitchRequestRetries = 5
@ -49,6 +51,7 @@ type (
accessToken string accessToken string
refreshToken string refreshToken string
tokenValidity time.Time tokenValidity time.Time
tokenValidityChecked time.Time
tokenUpdateHook func(string, string) error tokenUpdateHook func(string, string) error
appAccessToken string appAccessToken string
@ -577,12 +580,14 @@ func (c *Client) UpdateToken(accessToken, refreshToken string) {
} }
func (c *Client) ValidateToken(ctx context.Context, force bool) error { func (c *Client) ValidateToken(ctx context.Context, force bool) error {
if c.tokenValidity.After(time.Now()) && !force { if c.tokenValidity.After(time.Now()) && time.Since(c.tokenValidityChecked) < tokenValidityRecheckInterval && !force {
// We do have an expiration time and it's not expired // We do have an expiration time and it's not expired
// so we can assume we've checked the token and it should // so we can assume we've checked the token and it should
// still be valid. // still be valid.
// NOTE(kahlers): In case of a token revokation this // To detect a token revokation early-ish we re-check the
// assumption is invalid and will lead to failing requests // token in defined interval. This is not the optimal
// solution as we will get failing requests between revokation
// and recheck but it's better than nothing.
return nil return nil
} }
@ -611,6 +616,7 @@ func (c *Client) ValidateToken(ctx context.Context, force bool) error {
} }
c.tokenValidity = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second) c.tokenValidity = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second)
c.tokenValidityChecked = time.Now()
log.WithField("expiry", c.tokenValidity).Trace("Access token validated") log.WithField("expiry", c.tokenValidity).Trace("Access token validated")
return nil return nil