github webhooks

This commit is contained in:
Andras Bacsai
2023-05-09 14:42:10 +02:00
parent 19ad184cd6
commit 76bf601e1b
18 changed files with 217 additions and 20 deletions

View File

@@ -1,9 +1,14 @@
<?php
use App\Jobs\DeployApplicationJob;
use App\Models\Application;
use App\Models\PrivateKey;
use App\Models\GithubApp;
use App\Models\GithubEventsApplications;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
Route::get('/source/github/redirect', function () {
try {
@@ -50,3 +55,58 @@ Route::get('/source/github/install', function () {
return generalErrorHandler($e);
}
});
Route::post('/source/github/events', function () {
try {
$x_github_delivery = request()->header('X-GitHub-Delivery');
$x_github_event = Str::lower(request()->header('X-GitHub-Event'));
$x_github_hook_installation_target_id = request()->header('X-GitHub-Hook-Installation-Target-Id');
$x_hub_signature_256 = request()->header('X-Hub-Signature-256');
$payload = request()->collect();
if ($x_github_event === 'ping') {
// Just pong
return response('pong');
}
if ($x_github_event === 'installation') {
// Installation handled by setup redirect url. Repositories queried on-demand.
return response('cool');
}
$github_app = GithubApp::where('app_id', $x_github_hook_installation_target_id)->firstOrFail();
// TODO: Verify signature
// $webhook_secret = data_get($github_app, 'webhook_secret');
// $key = hash('sha256', $webhook_secret, true);
// $hmac = hash_hmac('sha256', request()->getContent(), $key);
// if (!hash_equals($hmac, $x_hub_signature_256)) {
// return response('not cool');
// }
if ($x_github_event === 'push') {
$id = data_get($payload, 'repository.id');
$branch = data_get($payload, 'ref');
if (Str::isMatch('/refs\/heads\/*/', $branch)) {
$branch = Str::after($branch, 'refs/heads/');
}
}
if ($x_github_event === 'pull_request') {
$id = data_get($payload, 'pull_request.base.repo.id');
$branch = data_get($payload, 'pull_request.base.ref');
}
if (!$id || !$branch) {
return response('not cool');
}
$applications = Application::where('project_id', $id)->where('git_branch', $branch)->get();
foreach ($applications as $application) {
GithubEventsApplications::create([
"delivery_guid" => $x_github_delivery,
"application_id" => $application->id
]);
$deployment_uuid = new Cuid2(7);
dispatch(new DeployApplicationJob(
deployment_uuid: $deployment_uuid,
application_uuid: $application->uuid,
force_rebuild: false,
));
}
} catch (\Exception $e) {
return generalErrorHandler($e);
}
});