+ // The oauth2 package will refresh the token when it is valid for less
+ // than 10 seconds. To avoid a race with later calls (which would
+ // refresh the token but the new RefreshToken wouldn't make it back
+ // into datastore), we refresh earlier than that. The Fitbit tokens are
+ // quite long-lived (six hours?); the additional load this puts on the
+ // backends is negligible.
+ if storedToken.Expiry.Round(0).Add(-5 * time.Minute).Before(time.Now()) {
+ storedToken.Expiry = time.Now()
+ }
+
+ refreshedToken, err := oauth2Config.TokenSource(ctx, storedToken).Token()
+ if err != nil {
+ return nil, err
+ }
+
+ if refreshedToken.RefreshToken != storedToken.RefreshToken {
+ if err := u.SetToken(ctx, "Fitbit", refreshedToken); err != nil {
+ return nil, err
+ }