32 lines
968 B
TypeScript
32 lines
968 B
TypeScript
import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
|
|
import AuthService from "@Services/common/AuthService/AuthService";
|
|
import { NextFunction, Request, Response } from "express";
|
|
import Container from "typedi";
|
|
|
|
export default function authHandler(req: Request, response: Response, next: NextFunction) {
|
|
try {
|
|
const authHeader = req.headers["authorization"];
|
|
const token = authHeader && authHeader.split(" ")[1];
|
|
|
|
if (!token) {
|
|
response.status(HttpCodes.UNAUTHORIZED).send("Missing token in authorization header");
|
|
return;
|
|
}
|
|
|
|
const authService = Container.get(AuthService);
|
|
authService.verifyAccessToken(token, (err, userPayload) => {
|
|
if (err) {
|
|
response.status(HttpCodes.UNAUTHORIZED).send("Error while verifying token");
|
|
return;
|
|
}
|
|
req.body.user = userPayload;
|
|
next();
|
|
});
|
|
|
|
} catch (error) {
|
|
console.log(error);
|
|
response.status(HttpCodes.INTERNAL_ERROR).send("Internal server error");
|
|
return;
|
|
}
|
|
}
|