-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgitee-webhook-handler.js
More file actions
89 lines (64 loc) · 2.19 KB
/
Copy pathgitee-webhook-handler.js
File metadata and controls
89 lines (64 loc) · 2.19 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
const EventEmitter = require('events').EventEmitter
, bl = require('bl')
function create (options) {
if (typeof options != 'object')
throw new TypeError('must provide an options object')
if (typeof options.path != 'string')
throw new TypeError('must provide a \'path\' option')
if (typeof options.token != 'string')
throw new TypeError('must provide a \'token\' option')
var events
if (typeof options.events == 'string' && options.events != '*')
events = [ options.events ]
else if (Array.isArray(options.events) && options.events.indexOf('*') == -1)
events = options.events
// make it an EventEmitter, sort of
handler.__proto__ = EventEmitter.prototype
EventEmitter.call(handler)
return handler
function handler (req, res, callback) {
if (req.url.split('?').shift() !== options.path || req.method !== 'POST')
return callback()
function hasError (msg) {
res.writeHead(400, { 'content-type': 'application/json' })
res.end(JSON.stringify({ error: msg }))
var err = new Error(msg)
handler.emit('error', err, req)
callback(err)
}
var agent = req.headers['user-agent']
, token = req.headers['x-gitee-token']
, event = req.headers['x-gitee-event']
if (agent !== 'git-oschina-hook')
return hasError('Invalid User-Agent')
if (!event)
return hasError('No X-Gitee-Event found on request')
if (token !== options.token)
return hasError('The token does not match')
if (events && events.indexOf(event) == -1)
return hasError('X-Gitee-Event is not acceptable')
req.pipe(bl(function (err, data) {
if (err) {
return hasError(err.message)
}
var obj
try {
obj = JSON.parse(data.toString())
} catch (e) {
return hasError(e)
}
res.writeHead(200, { 'content-type': 'application/json' })
res.end('{"ok":true}')
var emitData = {
event : event
, payload : obj
, protocol: req.protocol
, host : req.headers['host']
, url : req.url
}
handler.emit(event, emitData)
handler.emit('*', emitData)
}))
}
}
module.exports = create