From 039d3df7d806fd9fc602aaf5eef33cc774ac93f7 Mon Sep 17 00:00:00 2001 From: Michael Shamoon <4887959+shamoon@users.noreply.github.com> Date: Wed, 30 Nov 2022 09:35:18 -0800 Subject: [PATCH] Add token expiration, tweak error handling for npm --- src/widgets/npm/proxy.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/widgets/npm/proxy.js b/src/widgets/npm/proxy.js index ff15db62b..d6499e58c 100644 --- a/src/widgets/npm/proxy.js +++ b/src/widgets/npm/proxy.js @@ -20,12 +20,18 @@ async function login(loginUrl, username, password) { }); const status = authResponse[0]; - const data = JSON.parse(Buffer.from(authResponse[2]).toString()); - - if (status === 200) { - cache.put(tokenCacheKey, data.token); + let data = authResponse[2]; + + try { + data = JSON.parse(Buffer.from(authResponse[2]).toString()); + + if (status === 200) { + const expiration = new Date(data.expires) - Date.now(); + cache.put(tokenCacheKey, data.token, expiration - (5 * 60 * 1000)); // expiration -5 minutes + } + } catch (e) { + logger.error(`Error ${status} logging into npm`, authResponse[2]); } - return [status, data.token ?? data]; } @@ -51,8 +57,8 @@ export default async function npmProxyHandler(req, res) { if (!token) { [status, token] = await login(loginUrl, widget.username, widget.password); if (status !== 200) { - logger.debug(`HTTTP ${status} logging into npm api: ${data}`); - return res.status(status).send(data); + logger.debug(`HTTTP ${status} logging into npm api: ${token}`); + return res.status(status).send(token); } }