server: add basic jwt middleware tests

This commit is contained in:
Max Leiter 2022-04-06 09:28:01 -07:00
parent 6c39d1c7c0
commit 0e57e28b6c
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: A3512F2F2F17EBDA
2 changed files with 49 additions and 1 deletions

View file

@ -0,0 +1,48 @@
import jwt, { UserJwtRequest } from "@lib/middleware/jwt"
import { NextFunction, Response } from "express"
describe("jwt middlware", () => {
let mockRequest: Partial<UserJwtRequest>
let mockResponse: Partial<Response>
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)
// }
// })
})

View file

@ -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)