Skip to content

Commit

Permalink
try verify & parse req
Browse files Browse the repository at this point in the history
  • Loading branch information
olegakbarov committed Mar 7, 2017
1 parent 580f341 commit 0dec08d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
"license": "MIT",
"repository": "git@github.com:olegakbarov/facebook-messenger-devkit.git",
"dependencies": {
"body-parser": "^1.17.1",
"crypto": "0.0.3",
"eventsource": "^0.2.1",
"express": "^4.14.0"
}
Expand Down
30 changes: 28 additions & 2 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@

const EventEmitter = require('events');
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

const app = express();

app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.set('port', process.env.PORT || 3000);

app.get('/', (req, res) => {
Expand All @@ -28,12 +32,12 @@ const proxyEmitter = new SSE();
proxyEmitter.setMaxListeners(1);

app.post('/webhook', (req, res) => {
if (data.object === 'page') {
// if (data.object === 'page') {
proxyEmitter.emit('msg', req);

// timeout here = 20sec
res.sendStatus(200);
}
// }
});

// forward messages down to subscribed clients
Expand Down Expand Up @@ -66,4 +70,26 @@ app.all('/*', (req, res) => {
});
});

function verifyRequestSignature(req, res, buf) {
var signature = req.headers["x-hub-signature"];

if (!signature) {
// For testing, let's log an error. In production, you should throw an
// error.
console.error("Couldn't validate the signature.");
} else {
var elements = signature.split('=');
var method = elements[0];
var signatureHash = elements[1];

var expectedHash = crypto.createHmac('sha1', APP_SECRET)
.update(buf)
.digest('hex');

if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
}

app.listen(process.env.PORT || 5000)

0 comments on commit 0dec08d

Please sign in to comment.