From 9354feb98ccbf29291ee6606f9d1fb33d191d832 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me>
Date: Tue, 30 May 2023 18:06:53 +0200
Subject: [PATCH] Add a middleware for security verifications

---
 .../src/middlewares/SecurityMiddleware.ts     | 51 +++++++++++++++++++
 ExpressAPI/src/types/SecurityCheckType.ts     |  5 ++
 2 files changed, 56 insertions(+)
 create mode 100644 ExpressAPI/src/middlewares/SecurityMiddleware.ts
 create mode 100644 ExpressAPI/src/types/SecurityCheckType.ts

diff --git a/ExpressAPI/src/middlewares/SecurityMiddleware.ts b/ExpressAPI/src/middlewares/SecurityMiddleware.ts
new file mode 100644
index 0000000..73c5d82
--- /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 0000000..f865e13
--- /dev/null
+++ b/ExpressAPI/src/types/SecurityCheckType.ts
@@ -0,0 +1,5 @@
+enum SecurityCheckType {
+}
+
+
+export default SecurityCheckType;
-- 
GitLab