-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
59 lines (48 loc) · 1.49 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var express = require('express');
var bodyParser = require('body-parser');
var crypto = require('crypto');
const exec = require('child_process').exec;
// declare a new express app
var app = express()
app.use(bodyParser.json())
const SECRET = process.env.SECRET_TOKEN;
const repository = process.env.REPOSITORY;
const event = process.env.EVENT;
const PORT = process.env.PORT;
const GITHUB_BRANCHS_TO_SCRIPTS = {
'refs/heads/main': '/apps/main_build.sh',
'refs/heads/test': '/apps/test_build.sh',
};
//github webhook
app.post('/payload', function (req, res) {
//validate request
const signature = `sha1=${crypto
.createHmac('sha1', SECRET)
.update(JSON.stringify(req.body))
.digest('hex')}`;
if (signature != req.header('X-Hub-Signature')) {
return res.json({ message: "Invalid request!" })
}
//automation script
const isEvent = req.header("X-GitHub-Event") === event
const isRepository = req.body.repository.name === repository
if (isEvent && isRepository) {
const script = GITHUB_BRANCHS_TO_SCRIPTS[req.body.ref];
if (!script) {
return res.json({ message: "Branch not defined" })
}
try {
exec(`bash ${script}`);
console.log("script:", script)
return res.json({ message: "App updated" })
} catch (error) {
console.log(error);
return res.json({ message: "Script error" })
}
}
res.json({ message: "Received" })
})
app.listen(PORT, function () {
console.log(`App started on port ${PORT}`)
});
module.exports = app