forked from fiddus/github-webhooks-listener
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
153 lines (133 loc) · 6.32 KB
/
index.js
File metadata and controls
153 lines (133 loc) · 6.32 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
'use strict';
require("dotenv").config({path: __dirname + "/.env"});
const DeployTasks = require('./lib/deployTasks');
//Short code
function matchRule(str, rule) {
return new RegExp("^" + rule.split("*").join(".*") + "$").test(str);
}
function getDateTime() {
const now = new Date();
let year = now.getFullYear();
let month = now.getMonth()+1;
let day = now.getDate();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
if(month.toString().length === 1) {
month = '0'+month;
}
if(day.toString().length === 1) {
day = '0'+day;
}
if(hour.toString().length === 1) {
hour = '0'+hour;
}
if(minute.toString().length === 1) {
minute = '0'+minute;
}
if(second.toString().length === 1) {
second = '0'+second;
}
const dateTime = year+month+day+'-'+hour+minute+second;
return dateTime;
}
// example usage: realtime clock
console.log('TIME:',getDateTime());
console.log('option:',process.argv[2]);
const createNewConfig = process.argv[2]==='--config' || process.argv[2]==='--add';
const secret = process.env.DEPLOY_LISTENER_SECRET;
const sshKeyName = process.env.SSH_KEY_NAME || 'id_rsa';
if (!secret ) {
console.error('DEPLOY_LISTENER_SECRET is not defined');
} else if (!sshKeyName) {
console.error('SSH_KEY_NAME is not defined');
} else {
const express = require('express'),
app = express(),
server = require('http').createServer(app),
bodyParser = require('body-parser'),
verifyGitHubSignature = require('./lib/verifyGitHubSignature'),
getConfig = require('./lib/getConfig');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
verifyGitHubSignature.setSecret(secret);
getConfig(function (config) {
//for backward compatibity
if (config.branch && !config.projects) {
config.projects = [config];
}
app.post(config.route, function (req, res) {
console.log('received req',req);
for (const projectId in config.projects) {
const project = config.projects[projectId];
const deployTasks = new DeployTasks(project);
const cf_branch = project.branch || project.branch || 'master';
const cfTagSearch = project.tagsearch || project.tagsearch || undefined;
const cfRepo = project.repository_name || project.repository_name || undefined;
console.log('----- check config ',projectId,' -----');
console.log('checking on branch ',cf_branch, 'tag ',cfTagSearch);
// Checking if request is authentic
if (req.body
&& req.body.ref
&& req.body.repository
&& req.body.pusher
&& verifyGitHubSignature.ofRequest(req)
) {
// If master was updated, do stuff
const tag = req.body.ref.replace('refs/tags/', '');
const branch = req.body.ref.replace('refs/heads/', '');
const repository_name = req.body.repository.name;
const repository_ssh_url = req.body.repository.ssh_url;
const pusher_email = req.body.pusher.email;
const version = req.body.after || tag;
const message = req.body.head_commit && req.body.head_commit.message;
const datetime = getDateTime();
const params = Object.assign({},
project,{ tag, branch, repository_name, repository_ssh_url, pusher_email, version, message, datetime});
if (req.body.ref ) {
if (matchRule(req.body.ref, 'refs/tags/' + cfTagSearch)) {
if (req.body.created) {
if(project.checkDestinationDir && project.destinationDir){
console.log('checkDestinationDir not yet implemented');
}
console.log('Valid tag payload! Running commands with tag=',tag,'repository_name',repository_name);
deployTasks.run(function () {
res.status(200).send();
}, params);
} else {
console.log(`the received tag is not created`);
}
} else if (req.body.ref && req.body.ref === `refs/heads/${cf_branch}`) {
console.log('Found a valid payload! with branch=',cf_branch,'version=',version,'message=',message);
deployTasks.run(function () {
res.status(200).send();
}, params);
} else {
// if other branches were updated, send 200 only to make github happy...
cfTagSearch && console.log(`Received tag '${req.body.ref}' payload unrelated to ${'refs/tags/' + cfTagSearch} tag`);
cf_branch && console.log(`Received branch payload unrelated to ${cf_branch} branch`);
res.status(200).send();
}
} else {
console.log(`error received ref '${req.body.ref}' `);
}
} else {
console.warn('Received payload ref',req.body.ref);
if(!verifyGitHubSignature.ofRequest(req)) {
console.warn('Received payload with an invalid secret');
}else if (req.body) {
[ 'ref','repository', 'pusher', 'message','head_commit'].forEach(n =>
!req.body[n] && console.log('cannot found field ', n)
);
} else {
console.log('cannot find', body);
}
res.status(403).send();
}
}
});
server.listen(config.port, function () {
console.log(`Listening for webhook events on port ${config.port} on ${config.route}`);
});
}, createNewConfig);
}