Add Auth middleware;

This commit is contained in:
Stefan-5422
2022-03-23 12:59:33 +01:00
parent 4df48360b5
commit 67d4878c59
2 changed files with 57 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
import { authJwt } from "./controller/auth.controller";
declare module "express-serve-static-core" {
interface Request {
auth?: authJwt & { isAuthenthicated: boolean };
}
}
+50
View File
@@ -0,0 +1,50 @@
import { NextFunction, Request, Response } from "express";
import { createDefaultError } from "../lib/standardResponse";
import jwt, { JwtPayload } from "jsonwebtoken";
import { authJwt } from "../controller/auth.controller";
import prisma from "../lib/prisma.lib";
const verifyAuthorizationFormat = (authorization: string) => /^Bearer .+$/.test(authorization);
const getBearerToken = (authorization: string) => authorization.slice(7);
const JWT_SECRET = process.env.jwtsecret || "secret";
export const requireAuthentication = async (req: Request, res: Response, next: NextFunction) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(403).json(createDefaultError("The request did not contain a authorization header", null));
}
if (!verifyAuthorizationFormat(authorization)) {
return res.status(400).json(createDefaultError("Malformed Bearer Token", { format: "Bearer <token>" }));
}
let payload_: string | JwtPayload;
try {
payload_ = jwt.verify(getBearerToken(authorization), JWT_SECRET);
} catch (e) {
return res.status(403).json(createDefaultError("The Token could not be verified, it might be expiered", null));
}
const payload = payload_ as authJwt;
const { id } = payload;
const user = await prisma.user.findUnique({
where: { id },
select: {
role: true,
},
});
req.auth = {
isAuthenthicated: true,
id,
role: user?.role || "user",
};
next();
};