3 var env = require('gitter-web-env');
5 var winston = env.logger;
6 var config = env.config;
8 var crypto = require('crypto');
9 var eventService = require('gitter-web-events');
10 var troupeService = require('gitter-web-rooms/lib/troupe-service');
11 var checkRepoPrivacy = require('../../services/check-repo-privacy');
12 var StatusError = require('statuserror');
14 const WEBHOOKS_SECRET = config.get('webhooks:secret');
15 if (!WEBHOOKS_SECRET) {
16 winston.error('No webhooks secret provided');
19 // This is a bit of a hack, but it's somewhat useful:
20 // check to see whether a repo has been made public
21 function checkRepo(meta) {
22 var service = meta.service;
23 var event = meta.event;
26 if (service === 'github' && event === 'public' && repo) {
27 stats.event('webhook.github.public');
29 /* Do this asynchronously */
30 checkRepoPrivacy(repo).catch(function(err) {
31 winston.error('Repo privacy check failed: ' + err, { exception: err });
36 function decipherHash(hash) {
38 var decipher = crypto.createDecipher('aes256', WEBHOOKS_SECRET);
39 return decipher.update(hash, 'hex', 'utf8') + decipher.final('utf8');
45 module.exports = function(req, res, next) {
46 var troupeId = decipherHash(req.params.hash);
48 stats.event('webhook.invalid.hash');
49 return next(new StatusError(400, 'Invalid Troupe hash'));
52 var message = req.body.message;
53 var meta = req.body.meta;
54 var payload = req.body.payload;
62 .then(function(troupe) {
63 if (!troupe) return new StatusError(404);
65 return eventService.newEventToTroupe(troupe, null, message, meta, payload);
68 stats.event('webhook.receive.success');
71 .catch(function(err) {
72 stats.event('webhook.receive.failure');
73 if (err) winston.error('Error creating event: ' + err, { exception: err });