parent
0a3d943ca3
commit
a8c41b2268
39
src/validators/AdminGuard.ts
Normal file
39
src/validators/AdminGuard.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import JwtService from "@services/jwt.service";
|
||||||
|
import type {NextFunction, Request, Response} from "express";
|
||||||
|
import MySqlService from "@services/mysql.service";
|
||||||
|
import MysqlService from "@services/mysql.service";
|
||||||
|
import {Logger} from "tslog";
|
||||||
|
|
||||||
|
const DbHandler = new MySqlService.Handler('AdminGuard')
|
||||||
|
const logger = new Logger({name: 'AdminGuard'})
|
||||||
|
|
||||||
|
const UNAUTHORIZED = 401;
|
||||||
|
const FORBIDDEN = 403;
|
||||||
|
const UNAUTH_MESSAGE = 'Missing Authorization Header';
|
||||||
|
const INVALID_TOKEN_MESSAGE = 'Invalid or expired token.';
|
||||||
|
const PERMISSON_NOT_VALID = 'You are missing the required permission.'
|
||||||
|
|
||||||
|
async function AdminGuard(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
if (!authHeader) {
|
||||||
|
logger.warn(`Invalid header (${req.ip})`)
|
||||||
|
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 isSourceAdmin = await MysqlService.User.getAdminStateForId(DbHandler, token.sub)
|
||||||
|
if (isSourceAdmin === true) next();
|
||||||
|
return res.status(FORBIDDEN).json({message: PERMISSON_NOT_VALID});
|
||||||
|
|
||||||
|
}
|
||||||
|
return res.status(FORBIDDEN).json({message: INVALID_TOKEN_MESSAGE});
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AdminGuard
|
Loading…
x
Reference in New Issue
Block a user