import { Request, Response } from "express"; import jwt from "jsonwebtoken"; import BadRequestException from "../exceptions/badRequestException"; import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException"; import InternalException from "../exceptions/internalException"; import { JWTHelper } from "../helpers/jwtHelper"; export default async function authenticate(req: Request, res: Response, next: Function) { const bearer = req.headers.authorization?.split(" ")?.[1] ?? undefined; if (!bearer) { throw new BadRequestException("Provide valid Authorization Header"); } let decoded: string | jwt.JwtPayload; await JWTHelper.validate(bearer) .then((result) => { decoded = result; }) .catch((err) => { if (err == "jwt expired") { throw new UnauthorizedRequestException("Token expired"); } else { throw new BadRequestException("Failed Authorization Header decoding"); } }); if (typeof decoded == "string" || !decoded) { throw new InternalException("process failed"); } req.userId = decoded.userId; req.username = decoded.username; req.rights = decoded.rights; next(); }