From 289ee4abdf0eaaeb221145ae9979b2a4d8beb252 Mon Sep 17 00:00:00 2001 From: Hussein Kandil <101815486+hussein-m-kandil@users.noreply.github.com> Date: Thu, 18 Sep 2025 16:22:30 +0300 Subject: [PATCH] Ignore invalid token in `optionalAuthValidator` --- src/middlewares/validators.ts | 11 ++++++++++- src/tests/api/v1/posts.int.test.ts | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/middlewares/validators.ts b/src/middlewares/validators.ts index fb0942d..56f03c4 100644 --- a/src/middlewares/validators.ts +++ b/src/middlewares/validators.ts @@ -47,7 +47,16 @@ export const optionalAuthValidator = async ( next: NextFunction ) => { if (req.headers.authorization) { - await authValidator(req, res, next); + // The purpose of this middleware is to optionally retrieve user info + // if applicable, thereby preventing a 401 error on an invalid token + const callNext: unknown = () => next(); + const controlledRes = { + ...res, + sendStatus: callNext as typeof res.sendStatus, + send: callNext as typeof res.send, + end: callNext as typeof res.end, + } as Response; + await authValidator(req, controlledRes, callNext as NextFunction); } else next(); }; diff --git a/src/tests/api/v1/posts.int.test.ts b/src/tests/api/v1/posts.int.test.ts index 98651cc..1e16771 100644 --- a/src/tests/api/v1/posts.int.test.ts +++ b/src/tests/api/v1/posts.int.test.ts @@ -69,6 +69,23 @@ describe('Post endpoints', async () => { expect(resBody.length).toBe(0); }); + it('should respond with posts array on invalid auth token and not send 401', async () => { + const POST_COUNT = 2; + for (let i = 0; i < POST_COUNT; i++) { + await createPost(postFullData); + } + const res = await api.get(POSTS_URL).set('Authorization', 'blah'); + const resBody = res.body as PostFullData[]; + expect(res.statusCode).toBe(200); + expect(res.type).toMatch(/json/); + expect(resBody).toBeTypeOf('object'); + expect(Array.isArray(resBody)).toBe(true); + expect(resBody.length).toBe(POST_COUNT); + for (const post of resBody) { + assertPostData(post, postFullData); + } + }); + it('should respond with an array of posts with their images', async () => { const POST_COUNT = 2; const postData = { ...postFullData, image: dbImgOne.id };