Skip to content

Commit d9fe002

Browse files
Merge PR: Ignore invalid optional token
2 parents 4f69c9f + 289ee4a commit d9fe002

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/middlewares/validators.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,16 @@ export const optionalAuthValidator = async (
4747
next: NextFunction
4848
) => {
4949
if (req.headers.authorization) {
50-
await authValidator(req, res, next);
50+
// The purpose of this middleware is to optionally retrieve user info
51+
// if applicable, thereby preventing a 401 error on an invalid token
52+
const callNext: unknown = () => next();
53+
const controlledRes = {
54+
...res,
55+
sendStatus: callNext as typeof res.sendStatus,
56+
send: callNext as typeof res.send,
57+
end: callNext as typeof res.end,
58+
} as Response;
59+
await authValidator(req, controlledRes, callNext as NextFunction);
5160
} else next();
5261
};
5362

src/tests/api/v1/posts.int.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,23 @@ describe('Post endpoints', async () => {
6969
expect(resBody.length).toBe(0);
7070
});
7171

72+
it('should respond with posts array on invalid auth token and not send 401', async () => {
73+
const POST_COUNT = 2;
74+
for (let i = 0; i < POST_COUNT; i++) {
75+
await createPost(postFullData);
76+
}
77+
const res = await api.get(POSTS_URL).set('Authorization', 'blah');
78+
const resBody = res.body as PostFullData[];
79+
expect(res.statusCode).toBe(200);
80+
expect(res.type).toMatch(/json/);
81+
expect(resBody).toBeTypeOf('object');
82+
expect(Array.isArray(resBody)).toBe(true);
83+
expect(resBody.length).toBe(POST_COUNT);
84+
for (const post of resBody) {
85+
assertPostData(post, postFullData);
86+
}
87+
});
88+
7289
it('should respond with an array of posts with their images', async () => {
7390
const POST_COUNT = 2;
7491
const postData = { ...postFullData, image: dbImgOne.id };

0 commit comments

Comments
 (0)