diff --git a/ExpressAPI/src/middlewares/SecurityMiddleware.ts b/ExpressAPI/src/middlewares/SecurityMiddleware.ts new file mode 100644 index 0000000000000000000000000000000000000000..73c5d820891f904ad1c21eca8dfc0fb333255602 --- /dev/null +++ b/ExpressAPI/src/middlewares/SecurityMiddleware.ts @@ -0,0 +1,51 @@ +import express from 'express'; +import { StatusCodes } from 'http-status-codes'; +import SecurityCheckType from '../types/SecurityCheckType'; +import logger from '../shared/logging/WinstonLogger'; +import ApiRequest from '../models/ApiRequest'; + + +class SecurityMiddleware { + private static _instance: SecurityMiddleware; + + private constructor() { } + + public static get instance(): SecurityMiddleware { + if ( !SecurityMiddleware._instance ) { + SecurityMiddleware._instance = new SecurityMiddleware(); + } + + return SecurityMiddleware._instance; + } + + //Check if at least ONE rule match. It's NOT an AND but it's a OR function. For IsJuryUnlock, IsStudentUnlock and IsScheduleUnlock it's cumulative + check(...checkTypes: Array<SecurityCheckType>): (req: ApiRequest, res: express.Response, next: express.NextFunction) => void { + return async (req: ApiRequest, res: express.Response, next: express.NextFunction) => { + let isAllowed = checkTypes.length === 0; + + if ( !isAllowed ) { + for ( let checkType of checkTypes ) { + try { + switch ( checkType ) { + default: + isAllowed = isAllowed || false; + break; + } + } catch ( e ) { + logger.error('Security check failed !!! => ' + e); + isAllowed = isAllowed || false; + } + } + } + + if ( !isAllowed ) { + return req.session.sendResponse(res, StatusCodes.FORBIDDEN); + } + + return next(); + }; + } +} + + +export default SecurityMiddleware.instance; diff --git a/ExpressAPI/src/types/SecurityCheckType.ts b/ExpressAPI/src/types/SecurityCheckType.ts new file mode 100644 index 0000000000000000000000000000000000000000..f865e13ca58c8421c69afb9de9a24ea0612e59c4 --- /dev/null +++ b/ExpressAPI/src/types/SecurityCheckType.ts @@ -0,0 +1,5 @@ +enum SecurityCheckType { +} + + +export default SecurityCheckType;