From b8d73e3a94f81be26e5604d5ff4ddde8733786fb Mon Sep 17 00:00:00 2001 From: Douglas Barone Date: Mon, 19 Jun 2023 08:03:08 -0400 Subject: [PATCH] Handle expired tokens better --- src/controllers/AuthenticationController.ts | 2 +- src/middleware/injectUserMiddleware.ts | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/controllers/AuthenticationController.ts b/src/controllers/AuthenticationController.ts index ef4ddba..0f80b12 100644 --- a/src/controllers/AuthenticationController.ts +++ b/src/controllers/AuthenticationController.ts @@ -34,7 +34,7 @@ export class AuthenticationController { return user } catch (error: any) { - throw new Error('Invalid token') + throw new Error(`Invalid token. ${error.message}`) } } } diff --git a/src/middleware/injectUserMiddleware.ts b/src/middleware/injectUserMiddleware.ts index 0d7f455..bb6efe7 100644 --- a/src/middleware/injectUserMiddleware.ts +++ b/src/middleware/injectUserMiddleware.ts @@ -21,8 +21,12 @@ export async function injectUserMiddleware( const token = getToken(req) if (token) { - const user = await AuthenticationController.authenticate(token) - req.user = user + try { + const user = await AuthenticationController.authenticate(token) + req.user = user + } catch (error: any) { + return res.status(401).json({ error: error.message }) + } } next()