scope: services, interfaces subject: Apply code formatting - Correct indentation and formatting to match code style standards in multiple 'interfaces' and 'services' files. - Also ensure lines at the end of the files. Signed-off-by: Mathis <yidhra@tuta.io>
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import JwtService from "@services/jwt.service";
|
|
import MySqlService from "@services/mysql.service";
|
|
import type { NextFunction, Request, Response } from "express";
|
|
import { Logger } from "tslog";
|
|
|
|
const DbHandler = new MySqlService.Handler("UserGuard");
|
|
const logger = new Logger({
|
|
name: "UserGuard",
|
|
});
|
|
|
|
const UNAUTHORIZED = 401;
|
|
const FORBIDDEN = 403;
|
|
const UNAUTH_MESSAGE = "Missing Authorization Header";
|
|
const INVALID_TOKEN_MESSAGE = "Invalid or expired token.";
|
|
const USER_NOT_EXIST = "You dont exist anymore";
|
|
|
|
async function UserGuard(
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction,
|
|
) {
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader) {
|
|
return res.status(UNAUTHORIZED).json({
|
|
message: UNAUTH_MESSAGE,
|
|
});
|
|
}
|
|
|
|
const bearerToken = authHeader.split(" ")[1];
|
|
|
|
if (!bearerToken)
|
|
return res.status(FORBIDDEN).json({
|
|
message: INVALID_TOKEN_MESSAGE,
|
|
});
|
|
|
|
const token = await JwtService.verify(bearerToken);
|
|
|
|
if (token) {
|
|
// @ts-ignore
|
|
const userId = token.sub;
|
|
if (!userId) {
|
|
logger.error(USER_NOT_EXIST);
|
|
return res.status(UNAUTHORIZED).json({
|
|
message: USER_NOT_EXIST,
|
|
});
|
|
}
|
|
const user = await MySqlService.User.getById(
|
|
DbHandler,
|
|
userId,
|
|
);
|
|
if (user) {
|
|
logger.info(`An user do a request. (${user?.username})`);
|
|
next();
|
|
}
|
|
return res.status(UNAUTHORIZED).json({
|
|
message: USER_NOT_EXIST,
|
|
});
|
|
}
|
|
return res.status(FORBIDDEN).json({
|
|
message: INVALID_TOKEN_MESSAGE,
|
|
});
|
|
}
|
|
|
|
export default UserGuard;
|