webhook-api/event.php

64 lines
1.3 KiB
PHP
Raw Permalink Normal View History

2016-01-30 21:21:40 +01:00
<?php
function httpCode($code) {
http_response_code($code);
headers_sent();
}
function response(array $content, $code = 200) {
header('Content-type: application/json');
2016-01-30 21:42:21 +01:00
httpCode($code);
2016-01-30 21:21:40 +01:00
echo json_encode($content);
exit;
}
function badSecret() {
2016-01-30 21:42:21 +01:00
response(
[
'error' => 'Invalid secret',
],
403
);
2016-01-30 21:21:40 +01:00
}
function badRequest(array $content = []) {
2016-01-30 21:42:21 +01:00
response($content, 404);
2016-01-30 21:21:40 +01:00
}
function requiredBagVar($bag, $index) {
if (!array_key_exists($index, $bag)) {
badRequest([
'error' => 'Bad request',
'missing_param' => [$index, $bag],
]);
}
}
function isValidSecret($secret, $accounts) {
return in_array(
$secret,
$accounts
);
}
requiredBagVar($_POST, 'payload');
$payload = json_decode($_POST['payload'], true);
requiredBagVar($payload, 'secret');
$accounts = require 'accounts.php';
if (!isValidSecret($payload['secret'], $accounts)) {
badSecret();
}
$repository = preg_replace('/-project$/', '', $payload['repository']['name']);
$repository = str_replace(['/', '.'], '', $repository);
$command = 'sudo -u git $HOME/bin/webhook-project '.escapeshellarg($repository);
$execute = shell_exec($command);
response([
2016-01-30 21:42:21 +01:00
'action' => 'Gitnet project push event',
'output' => $execute,
2016-01-30 21:21:40 +01:00
]);