ff-admin-server/src/middleware/authenticate.ts

38 lines
1.2 KiB
TypeScript
Raw Normal View History

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) {
2024-08-23 07:44:36 +00:00
const bearer = req.headers.authorization?.split(" ")?.[1] ?? undefined;
if (!bearer) {
2024-08-23 07:44:36 +00:00
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;
2024-09-01 12:55:05 +00:00
req.permissions = decoded.permissions;
next();
}