From 5487a3a49be3164e87179b28b74f2ca7fc281a06 Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Sat, 26 Jul 2025 10:56:23 +0200 Subject: [PATCH] Catch JWT expiration. Closes #321 --- lib/www/server/api/middleware/auth/jwt.js | 17 ++++++++++++++++- lib/www/server/lib/jwt.js | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/www/server/api/middleware/auth/jwt.js b/lib/www/server/api/middleware/auth/jwt.js index da1c011..7fd9b40 100644 --- a/lib/www/server/api/middleware/auth/jwt.js +++ b/lib/www/server/api/middleware/auth/jwt.js @@ -11,12 +11,27 @@ const getToken = function (req) { return null; } +const onExpired = async function (req, err) { + // If it's not too badly expired, let it through + // and hope that a new token will be issued soon. + const elapsed = new Date() - err.inner.expiredAt; + // TODO: Add proper logging + // console.log("Expiry details (elapsed, gracePeriod)", elapsed, cfg.gracePeriod*1000); + if (elapsed < cfg.gracePeriod*1000) { + // console.log("JWT within grace period"); + return; + } + + throw err; +} + const options = { secret: cfg.secret, credentialsRequired: false, algorithms: ['HS256'], requestProperty: "user", - getToken + getToken, + onExpired }; module.exports = expressJWT(options); diff --git a/lib/www/server/lib/jwt.js b/lib/www/server/lib/jwt.js index db3343b..be52035 100644 --- a/lib/www/server/lib/jwt.js +++ b/lib/www/server/lib/jwt.js @@ -13,6 +13,20 @@ async function checkValidCredentials ({user, password, jwt}) { } catch (err) { console.warn("Failed to verify credentials for", jwt); console.warn(err); + + if (err instanceof JWT.TokenExpiredError) { + const payload = JWT.decode(jwt); + if (payload?.id) { + const user = await ServerUser.fromSQL(null, payload.id); + if (user?.active) { + // We should still be good, though the user might have + // change organisations and such. This will hopefully + // cause the JWT to be reissued. + return user.toJSON(); + } + } + } + return; // Invalid JWT } } else if (user && password) {