Skip to content

Commit fe82853

Browse files
committed
Refresh token if it will likely expire before the next validation
1 parent 9183d9a commit fe82853

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

twitchio/authentication/tokens.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,6 @@ def __init__(
9191
self._validate_task: asyncio.Task[None] | None = None
9292

9393
async def _attempt_refresh_on_add(self, token: str, refresh: str) -> ValidateTokenPayload:
94-
logger.debug("Token was invalid when attempting to add it to the token manager. Attempting to refresh.")
95-
9694
try:
9795
resp: RefreshTokenPayload = await self.__isolated.refresh_token(refresh)
9896
except HTTPException as e:
@@ -132,6 +130,7 @@ async def add_token(self, token: str, refresh: str) -> ValidateTokenPayload:
132130
msg: str = "Token was invalid. Please check the token or re-authenticate user with a new token."
133131
raise InvalidTokenException(msg, token=token, refresh=refresh, type_="token", original=e)
134132

133+
logger.debug("Token was invalid when attempting to add it to the token manager. Attempting to refresh.")
135134
return await self._attempt_refresh_on_add(token, refresh)
136135

137136
if not resp.login or not resp.user_id:
@@ -140,6 +139,10 @@ async def add_token(self, token: str, refresh: str) -> ValidateTokenPayload:
140139

141140
return resp
142141

142+
if resp.expires_in <= 3600:
143+
logger.debug("Token expires in %s seconds. Attempting to refresh.", resp.expires_in)
144+
return await self._attempt_refresh_on_add(token, refresh)
145+
143146
self._tokens[resp.user_id] = {
144147
"user_id": resp.user_id,
145148
"token": token,
@@ -268,13 +271,14 @@ async def _revalidate_all(self) -> None:
268271
logger.debug('Token for "%s" was invalid or expired. Attempting to refresh token.', user_id)
269272
await self._refresh_token(user_id, refresh)
270273
else:
271-
self._tokens[user_id]["last_validated"] = datetime.datetime.now().isoformat()
272-
273-
expires_in: int = valid_resp["expires_in"]
274-
if expires_in <= 300:
275-
logger.debug('Token for "%s" expires in %s seconds. Attempting to refresh token.', user_id, expires_in)
274+
if valid_resp.expires_in <= 3600:
275+
logger.debug(
276+
'Token for "%s" expires in %s seconds. Attempting to refresh token.', user_id, valid_resp.expires_in
277+
)
276278

277279
await self._refresh_token(user_id, refresh)
280+
else:
281+
self._tokens[user_id]["last_validated"] = datetime.datetime.now().isoformat()
278282

279283
async def __validate_loop(self) -> None:
280284
logger.debug("Started the token validation loop on %s.", self.__class__.__qualname__)

0 commit comments

Comments
 (0)