vendor/daniel-230/firehouse-interface/src/Services/RoutesService.php line 9

Open in your IDE?
  1. <?php
  2. namespace Daniel230\FirehouseInterface\Services;
  3. use Carbon\Carbon;
  4. use Composer\InstalledVersions;
  5. use Daniel230\FirehouseInterface\Clients\SystemClient;
  6. class RoutesService
  7. {
  8.     protected $redis;
  9.     protected $sysClient;
  10.     public function __construct()
  11.     {
  12.         $this->redis = new RedisService();
  13.         $this->sysClient = new SystemClient();
  14.         if ($this->isLaravel()) {
  15.             $this->registerLaravelRoute();
  16.         }
  17.         //  elseif ($this->isSymfony()) {
  18.         //     $this->registerSymfonyRoute();
  19.         // }
  20.     }
  21.     private function isLaravel()
  22.     {
  23.         return class_exists('Illuminate\Foundation\Application');
  24.     }
  25.     private function isSymfony()
  26.     {
  27.         return class_exists('Symfony\Component\HttpKernel\Kernel');
  28.     }
  29.     private function registerLaravelRoute()
  30.     {
  31.         // Laravel-specific endpoints
  32.         if (
  33.             class_exists('Illuminate\Support\Facades\Route') &&
  34.             class_exists('Illuminate\Http\Request')  &&
  35.             class_exists('Illuminate\Support\Facades\Validator')
  36.         ) {
  37.             //firehouse status
  38.             \Illuminate\Support\Facades\Route::get('/firehouse-status', function () {
  39.                 $systemStatus $this->getSystemStatus();
  40.                 return response()->json($systemStatus['data'], $systemStatus['status']);
  41.             });
  42.             \Illuminate\Support\Facades\Route::get('/firehouse-setup', function () {
  43.                 return response()->json('Access Denied'403);
  44.             });
  45.             //firehouse setup
  46.             \Illuminate\Support\Facades\Route::post('/firehouse-setup', function (\Illuminate\Http\Request $request) {
  47.                 $requestToken $request->get('request_token');
  48.                 $hmac $request->headers->get('x-fh-signature');
  49.                 $systemUpdateStatus = [];
  50.                 if (isset($requestToken)) {
  51.                     $systemUpdateStatus $this->requestCredentialsWithToken($requestToken);
  52.                     return response()->json($systemUpdateStatus$systemUpdateStatus['status']);
  53.                 } else if ($hmac) {
  54.                     $payload $request->request->all();
  55.                     $timestamp $request->get('timestamp');
  56.                     $updateSystem $this->updateSystem($hmac$payload$timestamp$payload['system_config']);
  57.                     $systemUpdateStatus $updateSystem;
  58.                 } else {
  59.                     return response()->json("Access Denied"403);
  60.                 }
  61.                 return response()->json($systemUpdateStatus$systemUpdateStatus['status']);
  62.             });
  63.         }
  64.         //CORS
  65.         if (class_exists('Illuminate\Support\Facades\Config')) {
  66.             // Append the dynamic route to CORS paths
  67.             \Illuminate\Support\Facades\Config::set('cors.paths'array_merge(
  68.                 config('cors.paths', []),
  69.                 ['/firehouse-status''/firehouse-setup']
  70.             ));
  71.         }
  72.     }
  73.     public function registerSymfonyStatusRoute()
  74.     {
  75.         // Check if the necessary classes exist in the Symfony context
  76.         if (class_exists('Symfony\Component\HttpFoundation\JsonResponse')) {
  77.             
  78.             $systemStatus $this->getSystemStatus();
  79.             return new \Symfony\Component\HttpFoundation\JsonResponse($systemStatus['data'], $systemStatus['status']);
  80.         }
  81.         return new \Symfony\Component\HttpFoundation\JsonResponse(['error' => 'JsonResponse class not found'], 500);
  82.     }
  83.     public function registerSymfonySetupRoute(\Symfony\Component\HttpFoundation\Request $request)
  84.     {
  85.         // Check if the necessary classes exist in the Symfony context
  86.         if (class_exists('Symfony\Component\HttpFoundation\Request') && class_exists('Symfony\Component\HttpFoundation\JsonResponse')) {
  87.             $requestToken $request->get('request_token');
  88.             $hmac $request->headers->get('x-fh-signature');
  89.             $systemUpdateStatus = [];
  90.             if (isset($requestToken)) {
  91.                 $systemUpdateStatus $this->requestCredentialsWithToken($requestToken);
  92.                 return new \Symfony\Component\HttpFoundation\JsonResponse($systemUpdateStatus$systemUpdateStatus['status']);
  93.             } else if ($hmac) {
  94.                 $payload $request->request->all();
  95.                 $timestamp $request->get('timestamp');
  96.                 $updateSystem $this->updateSystem($hmac$payload$timestamp$payload['system_config']);
  97.                 $systemUpdateStatus $updateSystem;
  98.             } else {
  99.                 return new \Symfony\Component\HttpFoundation\JsonResponse("Access Denied"403);
  100.             }
  101.             return new \Symfony\Component\HttpFoundation\JsonResponse($systemUpdateStatus$systemUpdateStatus['status']);
  102.         }
  103.         return new \Symfony\Component\HttpFoundation\JsonResponse("request failed"500);
  104.     }
  105.     public function requestCredentialsWithToken($requestToken)
  106.     {
  107.         $systemUpdateStatus = [];
  108.         $response $this->sysClient->remoteSetupRequest($requestToken);
  109.         if ($response->getStatusCode() == 200) {
  110.             $systemUpdateStatus['status'] = 200;
  111.             $encryptedCredentials json_decode($response->getResponseBody(), true);
  112.             $api_key $encryptedCredentials["api_key"] ?? null;
  113.             $api_secret $encryptedCredentials["api_secret"] ?? null;
  114.             if (isset($api_key) && isset($api_secret)) {
  115.                 $this->redis->setData('API_KEY'$api_key);
  116.                 $this->redis->setData('API_SECRET'$api_secret);
  117.                 $systemUpdateStatus['status'] = 200;
  118.                 $systemUpdateStatus['message'] = 'Api credentials setup succesfully';
  119.             } else {
  120.                 $systemUpdateStatus['status'] = 206;
  121.                 $systemUpdateStatus['message'] = 'Missing values';
  122.             }
  123.         } else {
  124.             $systemUpdateStatus['status'] = 400;
  125.             $systemUpdateStatus['message'] = 'Bad request';
  126.         }
  127.         return $systemUpdateStatus;
  128.     }
  129.     public function getSystemStatus() {
  130.         $response $this->sysClient->verifySystem();
  131.         if ($response->getStatusCode() == 200) {
  132.             $data json_decode($response->getResponseBody(), true);
  133.         } else {
  134.             $data["Error"] = "Invalid setup";
  135.         }
  136.         
  137.         // Add the plugin version to the data
  138.         $pluginName 'daniel-230/firehouse-interface';
  139.         if (class_exists(InstalledVersions::class) && InstalledVersions::isInstalled($pluginName)) {
  140.             $data['fh-version'] = InstalledVersions::getPrettyVersion($pluginName);
  141.         } else {
  142.             $data['fh-version'] = null;
  143.         }
  144.         return [
  145.             'status' => $response->getStatusCode(), // Assuming sysClient response has a getStatusCode method
  146.             'data' => $data,
  147.         ];
  148.     }
  149.     public function updateSystem($hmac$payload$timestamp$systemConfig)
  150.     {
  151.         $systemUpdateStatus = [];
  152.         $api_secret $this->redis->getData('API_SECRET');
  153.         $currentTime Carbon::now();
  154.         $maxAgeInSeconds 60;
  155.         // Check if the timestamp is within the last 5 minutes                
  156.         $acceptTime $currentTime->diffInSeconds(Carbon::createFromTimestamp($timestamp)) <= $maxAgeInSeconds;
  157.         if ($api_secret && $payload) {
  158.             if ($acceptTime) {
  159.                 $calculatedSignature hash_hmac('sha256'json_encode($payload), $api_secret);
  160.                 if (hash_equals($hmac$calculatedSignature)) {
  161.                     $systemUpdateStatus['status'] = 200;  // System request verified successfully
  162.                     // Check and handle system configuration
  163.                     if (isset($systemConfig)) {
  164.                         $updatedConfigs = [];
  165.                         $unsupportedConfigs = [];
  166.                         foreach ($systemConfig as $config) {
  167.                             // Generate the class name based on the config type
  168.                             $className str_replace(" """ucwords(str_replace("_"" "$config['type'])));
  169.                             $class 'Daniel230\\FirehouseInterface\\Models\\SystemConfigs\\' $className;
  170.                             if (class_exists($class)) {
  171.                                 // Instantiate the configuration class and save to Redis
  172.                                 $configClass = new $class($config['config']);
  173.                                 if (method_exists($configClass"toArray")) {
  174.                                     $this->redis->setData($classNamejson_encode($configClass->toArray()));
  175.                                     $updatedConfigs[] = $config['type'];
  176.                                 }
  177.                                 $systemUpdateStatus['redis_status'][$className] = $this->redis->getData($className);
  178.                                 $systemUpdateStatus['redis_status'][$className] = $this->redis->getData($className);
  179.                             } else {
  180.                                 // Track unsupported configurations
  181.                                 $unsupportedConfigs[] = $config['type'];
  182.                             }
  183.                         }
  184.                         $systemUpdateStatus['updated_configs'] = $updatedConfigs;
  185.                         if (!empty($unsupportedConfigs)) {
  186.                             if ($updatedConfigs) {
  187.                                 $systemUpdateStatus['status'] = 207;
  188.                             } else {
  189.                                 $systemUpdateStatus['status'] = 400;
  190.                             }
  191.                             $systemUpdateStatus['unsupported_configs'] = $unsupportedConfigs;  // Some configurations were unsupported
  192.                         }
  193.                     } else {
  194.                         $systemUpdateStatus['status'] = 400;
  195.                         $systemUpdateStatus['message'] = "Invalid config";
  196.                     }
  197.                 } else {
  198.                     $systemUpdateStatus['status'] = 403;
  199.                     $systemUpdateStatus['message'] = 'Access Denied';
  200.                 }
  201.             } else {
  202.                 $systemUpdateStatus['status'] = 403;
  203.                 $systemUpdateStatus['message'] = 'request not authorized';
  204.             }
  205.         } else {
  206.             $systemUpdateStatus['status'] = 500;
  207.             $systemUpdateStatus['message'] = 'request failed';
  208.         }
  209.         return $systemUpdateStatus;
  210.     }
  211. }