This repository has been archived by the owner on Mar 21, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhandler.js
71 lines (63 loc) · 2.22 KB
/
handler.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
71
'use strict';
var crypto = require('crypto')
, bufferEq = require('buffer-equal-constant-time')
, GitHubApi = require('github')
, parsePath = require('./labels/util/parse_path')
, processFiles = require('./labels/process')
, github = new GitHubApi();
github.authenticate({ type: 'oauth', token: process.env.GITHUB_TOKEN });
module.exports.receiveWebhook = (event, context, callback) => {
var body = JSON.parse(event['body']);
var eventType = event.headers['X-GitHub-Event'];
var eventGUID = event.headers['X-GitHub-Delivery'];
var signature = event.headers['X-Hub-Signature'];
if(eventType != 'pull_request' || body.action != 'opened') {
callback(null, buildResponse({'status': 'skipped', 'labels': []}));
return
}
console.log('Received event', JSON.stringify(event), JSON.stringify(body));
if(!verifySignature(process.env.GITHUB_SECRET, JSON.stringify(body), signature)) {
callback(new Error('[403] Expected signature did not match'), {'status': 'unexpected_signature'});
return
}
console.log('Received event of type', eventType);
github.pullRequests.getFiles({
owner: body.repository.owner.login,
repo: body.repository.name,
number: body.number
}, function(err, files){
if(err) {
callback(new Error(err));
return
}
const labels = processFiles(body, github, files);
console.log('Adding labels', labels);
if (labels.length > 0 && labels.length < 10) {
github.issues.addLabels({
owner: body.repository.owner.login,
repo: body.repository.name,
number: body.number,
labels: labels
}, function(err, resp){
callback(err, buildResponse({'status': 'ok', 'labels': labels}));
return
});
} else {
callback(null, buildResponse({'status': 'skipped', 'labels': labels}));
return
}
});
};
function signData(secret, data) {
return 'sha1=' + crypto.createHmac('sha1', secret).update(data, 'utf-8').digest('hex');
}
function verifySignature(secret, data, signature) {
return bufferEq(new Buffer(signature), new Buffer(signData(secret, data)));
}
function buildResponse(json){
return {
statusCode: (json.status === 'ok') ? 201 : 200,
headers: {},
body: JSON.stringify(json)
};
}