feat: UserGuard

#10
This commit is contained in:
Mathis H (Avnyr) 2024-04-23 12:00:14 +02:00
parent c334b3954f
commit 0a3d943ca3
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -0,0 +1,40 @@
import JwtService from "@services/jwt.service";
import type {NextFunction, Request, Response} from "express";
import MySqlService from "@services/mysql.service";
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;
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