|
| 1 | +<?php |
| 2 | +namespace Flowpack\Prunner\Controller; |
| 3 | + |
| 4 | +use Firebase\JWT\JWT; |
| 5 | +use GuzzleHttp\Client; |
| 6 | +use Neos\Flow\Annotations as Flow; |
| 7 | +use Symfony\Component\Yaml\Exception\ParseException; |
| 8 | +use Symfony\Component\Yaml\Yaml; |
| 9 | + |
| 10 | +class ProxyController extends \Neos\Flow\Mvc\Controller\ActionController |
| 11 | +{ |
| 12 | + |
| 13 | + /** |
| 14 | + * @Flow\InjectConfiguration(path="apiBaseUrl") |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + protected $apiBaseUrl; |
| 18 | + |
| 19 | + /** |
| 20 | + * @Flow\InjectConfiguration(path="directory") |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + protected $directory; |
| 24 | + |
| 25 | + /** |
| 26 | + * @Flow\InjectConfiguration(path="jwtSecret") |
| 27 | + * @var string |
| 28 | + */ |
| 29 | + protected $jwtSecret; |
| 30 | + |
| 31 | + /** |
| 32 | + * @Flow\Inject |
| 33 | + * @var \Neos\Flow\Security\Context |
| 34 | + */ |
| 35 | + protected $context; |
| 36 | + |
| 37 | + public function indexAction(string $path, string $subpath) |
| 38 | + { |
| 39 | + // Simple workaround to have slashes in route parts... |
| 40 | + $apiPath = $path; |
| 41 | + if ($subpath !== '') { |
| 42 | + $apiPath .= '/' . $subpath; |
| 43 | + } |
| 44 | + $url = rtrim($this->apiBaseUrl, '/') . '/' . $apiPath; |
| 45 | + |
| 46 | + // Create JWT token for user |
| 47 | + |
| 48 | + if (!empty($this->jwtSecret)) { |
| 49 | + $jwtSecret = $this->jwtSecret; |
| 50 | + } else { |
| 51 | + try { |
| 52 | + // Try to parse prunner config to get JWT secret |
| 53 | + $config = Yaml::parseFile($this->directory . '/.prunner.yml'); |
| 54 | + $jwtSecret = $config['jwt_secret']; |
| 55 | + } catch (ParseException $e) { |
| 56 | + $this->response->setContentType('application/json'); |
| 57 | + $this->response->setStatusCode(500); |
| 58 | + return json_encode(['error' => 'Invalid prunner configuration']); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + $accountIdentifier = $this->context->getAccount()->getAccountIdentifier(); |
| 63 | + |
| 64 | + // Generate JWT token on the fly with expiration in 60 seconds |
| 65 | + $authToken = JWT::encode([ |
| 66 | + 'sub' => $accountIdentifier, |
| 67 | + 'exp' => time() + 60 |
| 68 | + ], $jwtSecret, 'HS256'); |
| 69 | + |
| 70 | + $client = new Client(); |
| 71 | + $response = $client->request($this->request->getHttpRequest()->getMethod(), $url, [ |
| 72 | + 'headers' => [ |
| 73 | + 'Authorization' => 'Bearer ' . $authToken |
| 74 | + ], |
| 75 | + 'body' => $this->request->getHttpRequest()->getBody(), |
| 76 | + 'http_errors' => false |
| 77 | + ]); |
| 78 | + |
| 79 | + $this->response->setContentType('application/json'); |
| 80 | + $this->response->setStatusCode($response->getStatusCode()); |
| 81 | + |
| 82 | + return $response->getBody(); |
| 83 | + } |
| 84 | +} |
0 commit comments