38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
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", err);
|
|
} else {
|
|
throw new BadRequestException("Failed Authorization Header decoding", err);
|
|
}
|
|
});
|
|
|
|
if (typeof decoded == "string" || !decoded) {
|
|
throw new InternalException("process failed");
|
|
}
|
|
|
|
req.userId = decoded.userId;
|
|
req.username = decoded.username;
|
|
req.isOwner = decoded.isOwner;
|
|
req.permissions = decoded.permissions;
|
|
|
|
next();
|
|
}
|