webhook code for automaticl deployment
This commit is contained in:
64
webhook.js
Normal file
64
webhook.js
Normal file
@@ -0,0 +1,64 @@
|
||||
const http = require('http');
|
||||
const { exec } = require('child_process');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// Your Gitea webhook secret
|
||||
const WEBHOOK_SECRET = 'your-secret-here';
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'POST') {
|
||||
let body = '';
|
||||
|
||||
req.on('data', chunk => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
|
||||
req.on('end', () => {
|
||||
// Verify webhook signature if Gitea is configured to send one
|
||||
const signature = req.headers['x-gitea-signature'];
|
||||
if (signature) {
|
||||
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
|
||||
const digest = hmac.update(body).digest('hex');
|
||||
if (digest !== signature) {
|
||||
res.writeHead(401);
|
||||
res.end('Invalid signature');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(body);
|
||||
|
||||
// Check if this is a push event
|
||||
if (payload.ref === 'refs/heads/main') { // or your default branch
|
||||
exec('bash deploy.sh', (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error(`Error: ${error}`);
|
||||
res.writeHead(500);
|
||||
res.end('Deployment failed');
|
||||
return;
|
||||
}
|
||||
console.log(`Deployment successful: ${stdout}`);
|
||||
res.writeHead(200);
|
||||
res.end('Deployment successful');
|
||||
});
|
||||
} else {
|
||||
res.writeHead(200);
|
||||
res.end('Not a push to main branch');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing webhook:', error);
|
||||
res.writeHead(400);
|
||||
res.end('Invalid payload');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
res.writeHead(405);
|
||||
res.end('Method not allowed');
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Webhook server listening on port ${PORT}`);
|
||||
});
|
Reference in New Issue
Block a user