-
Notifications
You must be signed in to change notification settings - Fork 0
/
uphook.js
70 lines (62 loc) · 2.08 KB
/
uphook.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
60
61
62
63
64
65
66
67
68
69
70
'use strict';
let bluebird = require('bluebird');
let exec = bluebird.promisify(require('child_process').exec);
let branch = require('git-branch').sync(); //meh, it could change the branch mid-execution but like that's even more problematic
let bodyParser = require('body-parser');
let crypto = require('crypto');
let fs = require('fs');
//Careful, as this erases all tracked changes.
//todo: generalize to default to tracked branch but be able to pull from any remote
function gitupdate(req, res, callback){
let promise = exec('git fetch --all && git reset --hard origin/' + branch + ' && npm install && npm prune')
.spread(function(stdout, stderr){
console.log(stdout, stderr);
res.sendStatus(200);
callback(null, req.body);
});
if(callback)
return promise.catch(function(err){
console.error(err);
res.sendStatus(500);
callback(err, req.body);
});
else
return promise;
}
let generalized = function(options, checkHeaders){
let secret = options.secret;
if(!secret) throw new Error('No secret given');
let verify = options.verify || function(){return true;}
let callback = options.callback || function(){};
return [
bodyParser.json({
verify: function(req, res, buffer){
req.digest = function(){
return 'sha1=' + crypto.createHmac('sha1', secret).update(buffer).digest('hex');
};
}
}),
function (req, res, next){
if(!checkHeaders(req))
res.sendStatus(403);
else if(!verify(req, res))
res.sendStatus(500);
else
gitupdate(req, res, callback);
}
];
}
module.exports.github = function(options){
return generalized(options, function(req){
return (req.headers['x-hub-signature'] == req.digest()
&& req.headers['x-github-event'] == 'push'
&& req.body.ref == 'refs/heads/' + branch);
});
};
module.exports.gitlab = function(options){
return generalized(options, function(req){
return (req.headers['x-gitlab-token'] == secret
&& req.headers['x-gitlab-event'] == 'Push Hook'
&& req.body.ref == 'refs/heads/' + branch);
});
};