diff --git a/server/src/lib/__tests__/middleware/jwt.ts b/server/src/lib/__tests__/middleware/jwt.ts new file mode 100644 index 00000000..4e869de4 --- /dev/null +++ b/server/src/lib/__tests__/middleware/jwt.ts @@ -0,0 +1,48 @@ +import jwt, { UserJwtRequest } from "@lib/middleware/jwt" +import { NextFunction, Response } from "express" + +describe("jwt middlware", () => { + let mockRequest: Partial + let mockResponse: Partial + let nextFunction: NextFunction = jest.fn() + + beforeEach(() => { + mockRequest = {} + mockResponse = { + sendStatus: jest.fn().mockReturnThis(), + } + }) + + it("should return 401 if no authorization header", () => { + const res = mockResponse as Response + jwt(mockRequest as UserJwtRequest, res, nextFunction) + expect(res.sendStatus).toHaveBeenCalledWith(401) + }) + + it("should return 401 if no token is supplied", () => { + const req = mockRequest as UserJwtRequest + req.headers = { + authorization: "Bearer" + } + jwt(req, mockResponse as Response, nextFunction) + expect(mockResponse.sendStatus).toBeCalledWith(401) + }) + + // it("should return 401 if token is deleted", async () => { + // try { + // const tokenString = "123" + + // const req = mockRequest as UserJwtRequest + // req.headers = { + // authorization: `Bearer ${tokenString}` + // } + // jwt(req, mockResponse as Response, nextFunction) + // expect(mockResponse.sendStatus).toBeCalledWith(401) + // expect(mockResponse.json).toBeCalledWith({ + // message: "Token is no longer valid" + // }) + // } catch (e) { + // console.log(e) + // } + // }) +}) \ No newline at end of file diff --git a/server/src/lib/middleware/jwt.ts b/server/src/lib/middleware/jwt.ts index ce273073..553c4bba 100644 --- a/server/src/lib/middleware/jwt.ts +++ b/server/src/lib/middleware/jwt.ts @@ -17,7 +17,7 @@ export default async function authenticateToken( res: Response, next: NextFunction ) { - const authHeader = req.headers["authorization"] + const authHeader = req.headers ? req.headers["authorization"] : undefined const token = authHeader && authHeader.split(" ")[1] if (token == null) return res.sendStatus(401)