implemented the GitHub calls for the repository

This commit is contained in:
stephan.kasdorf
2024-06-18 16:58:02 +02:00
parent 2572c28648
commit a3b811ec9a
20 changed files with 552 additions and 166 deletions

View File

@@ -0,0 +1 @@
<?php

View File

@@ -0,0 +1,261 @@
<?php
namespace NibiruWebhookReceiver;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use GuzzleHttp\Client;
class WebhookController
{
private $secretKey;
private $authApiUrl;
private $githubToken;
private $repoOwner;
private $repoName;
private $client;
private $githubApiUrl;
public function __construct()
{
$this->secretKey = getenv('JWT_SECRET_KEY');
$this->authApiUrl = getenv('NIBIRU_AUTH_API_URL');
$this->githubToken = getenv('GITHUB_TOKEN');
$this->repoOwner = getenv('GITHUB_REPO_OWNER');
$this->repoName = getenv('GITHUB_REPO_NAME');
$this->githubApiUrl = getenv('GITHUB_REPOSITORY_API_URL');
$this->client = new Client();
}
/**
* @desc handle the webhook request and validate the token
* @return void
*/
public function handleWebhook()
{
$token = $this->getBearerToken();
// Debug output for token
error_log("Received Token: " . $token);
if ($token)
{
try {
$decoded = JWT::decode($token, new Key($this->secretKey, 'HS256'));
$payload = (array) $decoded;
// Token is valid, process the webhook
http_response_code(200);
echo json_encode(['message' => 'Webhook processed', 'data' => $payload]);
} catch (\Exception $e) {
// Invalid token
http_response_code(401);
echo json_encode(['error' => 'Invalid token', 'message' => $e->getMessage()]);
}
} else {
// No token provided
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
}
}
/**
* @desc get file content from the GitHub repository
* @return void*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function listFiles()
{
$token = $this->getBearerToken();
if ($token)
{
try {
JWT::decode($token, new Key($this->secretKey, 'HS256'));
$response = $this->client->get("{$this->githubApiUrl}/repos/{$this->repoOwner}/{$this->repoName}/contents", [
'headers' => [
'Authorization' => "Bearer {$this->githubToken}",
'Accept' => 'application/vnd.github.v3+json',
],
]);
$data = json_decode($response->getBody(), true);
http_response_code(200);
echo json_encode($data);
} catch (\Exception $e) {
http_response_code(401);
echo json_encode(['error' => 'Invalid token', 'message' => $e->getMessage()]);
}
} else {
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
}
}
/**
* @desc get file content from the GitHub repository
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function getFile()
{
$token = $this->getBearerToken();
$filePath = $_GET['path'] ?? '';
if ($token)
{
try {
JWT::decode($token, new Key($this->secretKey, 'HS256'));
$response = $this->client->get("{$this->githubApiUrl}/repos/{$this->repoOwner}/{$this->repoName}/contents/{$filePath}", [
'headers' => [
'Authorization' => "Bearer {$this->githubToken}",
'Accept' => 'application/vnd.github.v3+json',
],
]);
$data = json_decode($response->getBody(), true);
http_response_code(200);
echo json_encode($data);
} catch (\Exception $e) {
http_response_code(401);
echo json_encode(['error' => 'Invalid token', 'message' => $e->getMessage()]);
}
} else {
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
}
}
/**
* @desc list tags from the GitHub repository
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function listTags()
{
$token = $this->getBearerToken();
if ($token)
{
try {
JWT::decode($token, new Key($this->secretKey, 'HS256'));
$response = $this->client->get("{$this->githubApiUrl}/repos/{$this->repoOwner}/{$this->repoName}/tags", [
'headers' => [
'Authorization' => "Bearer {$this->githubToken}",
'Accept' => 'application/vnd.github.v3+json',
],
]);
$data = json_decode($response->getBody(), true);
http_response_code(200);
echo json_encode($data);
} catch (\Exception $e) {
http_response_code(401);
echo json_encode(['error' => 'Invalid token', 'message' => $e->getMessage()]);
}
} else {
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
}
}
/**
* @desc get authentication header
* @return string|null
*/
private function getAuthorizationHeader()
{
$headers = null;
if (isset($_SERVER['Authorization']))
{
$headers = trim($_SERVER["Authorization"]);
} elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if (isset($requestHeaders['Authorization']))
{
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* @desc Get the Bearer token from the Authorization header
* @return string|null
*/
private function getBearerToken()
{
$headers = $this->getAuthorizationHeader();
if (!empty($headers))
{
if (preg_match('/Bearer\s(\S+)/', $headers, $matches))
{
return $matches[1];
}
}
return null;
}
/**
* @desc Split API methods calls in order to handled multiple actions
* @return void
*/
public function handle()
{
$action = $_GET['action'] ?? null;
switch ($action) {
case 'webhook':
$this->handleWebhook();
break;
case 'list-files':
$this->listFiles();
break;
case 'get-file':
$this->getFile();
break;
case 'list-tags':
$this->listTags();
break;
default:
http_response_code(404);
echo "Action not found.";
break;
}
}
private function validateToken($authHeader)
{
$ch = curl_init("{$this->authApiUrl}/index.php?action=validate");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: $authHeader"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode === 200;
}
private function processPayload($payload)
{
// Add your payload processing logic here
// For example, you could log the payload or trigger some other action
$this->response(['message' => 'Webhook received'], 200);
}
private function response($data, $status)
{
header("Content-Type: application/json", true, $status);
echo json_encode($data);
exit;
}
}

View File

@@ -0,0 +1,62 @@
<?php
require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
// Function to get the Authorization header
function getAuthorizationHeader()
{
$headers = null;
if (isset($_SERVER['Authorization']))
{
$headers = trim($_SERVER["Authorization"]);
} elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { // Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if (isset($requestHeaders['Authorization']))
{
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
// Function to get the Bearer token from the Authorization header
function getBearerToken()
{
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers))
{
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
// Get the token from the Authorization header
$token = getBearerToken();
if ($token)
{
try {
$secretKey = getenv('JWT_SECRET_KEY'); // Ensure this is set in your environment
$decoded = JWT::decode($token, $secretKey, ['HS256']);
$payload = (array) $decoded;
// Token is valid, process the webhook
http_response_code(200);
echo json_encode(['message' => 'Webhook processed', 'data' => $payload]);
} catch (Exception $e) {
// Invalid token
http_response_code(401);
echo json_encode(['error' => 'Invalid token', 'message' => $e->getMessage()]);
}
} else {
// No token provided
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
}

View File

@@ -0,0 +1,27 @@
{
"name": "nibiru/webhook-receiver",
"description": "Webhook Receiver for Nibiru Framework",
"type": "project",
"require": {
"guzzlehttp/guzzle": "^7.0",
"psr/http-message": "^1.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"symfony/deprecation-contracts": "^2.1",
"firebase/php-jwt": "^6.0"
},
"autoload": {
"psr-4": {
"NibiruWebhookReceiver\\": ""
}
},
"config": {
"optimize-autoloader": true,
"sort-packages": true
},
"scripts": {
"post-update-cmd": [
"chmod -R 777 storage"
]
}
}

View File

@@ -0,0 +1,6 @@
<?php
require __DIR__ . '/vendor/autoload.php';
use NibiruWebhookReceiver\WebhookController;
$webhookController = new WebhookController();
$webhookController->handle();