From a534038b11c7ce734edeba3368b6632add1b865f Mon Sep 17 00:00:00 2001
From: unknown <13521043@std.stei.itb.ac.id>
Date: Tue, 31 Oct 2023 09:42:04 +0700
Subject: [PATCH] Update ControllerWrapper.php

---
 src/controller/ControllerWrapper.php | 41 ++++++++++++++++++----------
 1 file changed, 26 insertions(+), 15 deletions(-)

diff --git a/src/controller/ControllerWrapper.php b/src/controller/ControllerWrapper.php
index 701ea8f..54a7541 100644
--- a/src/controller/ControllerWrapper.php
+++ b/src/controller/ControllerWrapper.php
@@ -1,13 +1,17 @@
 <?php
 
 require_once __DIR__ . "/BaseController.php";
+require_once __DIR__ . "/../middleware/ApiKeyHandler.php";
 
 class ControllerWrapper
 {
     private BaseController $controller;
+    private string $apiKey;
 
     public function __construct(BaseController $controller)
     {
+        $headers = getallheaders();
+        $this->apiKey = $headers['X-API-KEY'] ?? '';    
         $this->controller = $controller;
     }
 
@@ -24,25 +28,32 @@ class ControllerWrapper
     }
 
     public function respond()
-    {
-        $requestMethod = strtoupper($_SERVER["REQUEST_METHOD"]);
-
+    {   
+        $apiKeyHandler = ApiKeyHandler::getInstance();
+        $res = $apiKeyHandler->checkApiKey($this->apiKey);
         $strErrorDesc = '';
         $strErrorHeader = '';
 
-        $responseData = [];
-
-        try {
-            $this->controller->respond($requestMethod, $responseData, $strErrorDesc, $strErrorHeader);
-        } catch (Error $e) {
-            $strErrorDesc = $e->getMessage() . ' . Something went wrong!';
-            $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
-        } catch (ServiceException $e) {
-            $strErrorDesc = (string) "Service Exception Encountered";
-            $strErrorHeader = 'HTTP/1.1 400 Bad Request';
-        } catch (Exception $e) {
-            $strErrorDesc = $e->getMessage();
+        if (!$res) {
+            $strErrorDesc = 'Invalid API Key';
             $strErrorHeader = 'HTTP/1.1 400 Bad Request';
+        } else {
+            $requestMethod = strtoupper($_SERVER["REQUEST_METHOD"]);
+    
+            $responseData = [];
+    
+            try {
+                $this->controller->respond($requestMethod, $responseData, $strErrorDesc, $strErrorHeader);
+            } catch (Error $e) {
+                $strErrorDesc = $e->getMessage() . ' . Something went wrong!';
+                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
+            } catch (ServiceException $e) {
+                $strErrorDesc = (string) "Service Exception Encountered";
+                $strErrorHeader = 'HTTP/1.1 400 Bad Request';
+            } catch (Exception $e) {
+                $strErrorDesc = $e->getMessage();
+                $strErrorHeader = 'HTTP/1.1 400 Bad Request';
+            }
         }
 
         // send output 
-- 
GitLab