|
1 | 1 | <?php |
2 | 2 |
|
3 | | -namespace Stackkit\LaravelGoogleCloudTasksQueue; |
| 3 | +namespace Stackkit\LaravelGoogleCloudScheduler; |
| 4 | + |
| 5 | +use Firebase\JWT\JWT; |
| 6 | +use Illuminate\Http\Request; |
| 7 | +use Illuminate\Support\Facades\Artisan; |
4 | 8 |
|
5 | 9 | class TaskHandler |
6 | 10 | { |
| 11 | + private $command; |
| 12 | + private $request; |
| 13 | + private $openId; |
| 14 | + private $jwt; |
| 15 | + |
| 16 | + public function __construct(Command $command, Request $request, OpenIdVerificator $openId, JWT $jwt) |
| 17 | + { |
| 18 | + $this->command = $command; |
| 19 | + $this->request = $request; |
| 20 | + $this->openId = $openId; |
| 21 | + $this->jwt = $jwt; |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * @throws CloudSchedulerException |
| 26 | + */ |
7 | 27 | public function handle() |
8 | 28 | { |
9 | | - // |
| 29 | + $this->authorizeRequest(); |
| 30 | + |
| 31 | + set_time_limit(0); |
| 32 | + |
| 33 | + Artisan::call($this->command->captureWithoutArtisan()); |
| 34 | + |
| 35 | + $output = Artisan::output(); |
| 36 | + |
| 37 | + logger($output); |
| 38 | + |
| 39 | + return $this->cleanOutput($output); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @throws CloudSchedulerException |
| 44 | + */ |
| 45 | + private function authorizeRequest() |
| 46 | + { |
| 47 | + if (!$this->request->hasHeader('Authorization')) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + $openIdToken = $this->request->bearerToken(); |
| 52 | + $kid = $this->openId->getKidFromOpenIdToken($openIdToken); |
| 53 | + $publicKey = $this->openId->getPublicKey($kid); |
| 54 | + |
| 55 | + $decodedToken = $this->jwt->decode($openIdToken, $publicKey, ['RS256']); |
| 56 | + |
| 57 | + $this->validateToken($decodedToken); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * https://developers.google.com/identity/protocols/oauth2/openid-connect#validatinganidtoken |
| 62 | + * |
| 63 | + * @param $openIdToken |
| 64 | + * @throws CloudSchedulerException |
| 65 | + */ |
| 66 | + protected function validateToken($openIdToken) |
| 67 | + { |
| 68 | + if (!in_array($openIdToken->iss, ['https://accounts.google.com', 'accounts.google.com'])) { |
| 69 | + throw new CloudSchedulerException('The given OpenID token is not valid'); |
| 70 | + } |
| 71 | + |
| 72 | + if ($openIdToken->exp < time()) { |
| 73 | + throw new CloudSchedulerException('The given OpenID token has expired'); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + private function cleanOutput($output) |
| 78 | + { |
| 79 | + return trim($output); |
10 | 80 | } |
11 | 81 | } |
0 commit comments