From 83f825c2f952f9714cd37e9f3ca83bb76b817e0d Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Wed, 5 Jul 2017 02:38:35 +0000 Subject: [PATCH] add twilio body parser and other tel stuff --- lib/apis.js | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/apis.js b/lib/apis.js index 915d42f..bed3111 100644 --- a/lib/apis.js +++ b/lib/apis.js @@ -430,12 +430,13 @@ module.exports.create = function (xconfx, apiFactories, apiDeps) { } }); + if (xconfx.debug) { console.log('[api.js] twilio added'); } + var Twilio = require('twilio'); function twilioTel(/*opts*/) { if (_twilio) { return _twilio; } - var Twilio = require('twilio'); _twilio = new Twilio.RestClient( siteConfig['twilio.com'].live.id , siteConfig['twilio.com'].live.auth @@ -443,12 +444,35 @@ module.exports.create = function (xconfx, apiFactories, apiDeps) { return apiDeps.Promise.resolve(_twilio); } - var bodyParserTwilio = require('body-parser').urlencoded({ limit: '4kb', parameterLimit: 25, extended: false }); + // Twilio Parameters are often 26 long + var bodyParserTwilio = require('body-parser').urlencoded({ limit: '4kb', parameterLimit: 100, extended: false }); var caps = { 'twilio@daplie.com': twilioTel , 'com.daplie.tel.twilio': twilioTel // deprecated , 'twilio.urlencoded@daplie.com': function (req, res, next) { - return bodyParserTwilio(req, res, next); + // TODO null for res and Promise instead of next? + return bodyParserTwilio(req, res, function () { + var signature = req.headers['x-twilio-signature']; + var auth = siteConfig['twilio.com'].live.auth; + var fullUrl = 'https://' + req.headers.host + req._walnutOriginalUrl; + var validSig = Twilio.validateRequest(auth, signature, fullUrl, req.body); + /* + console.log('Twilio Signature Check'); + console.log('auth', auth); + console.log('sig', signature); + console.log('fullUrl', fullUrl); + console.log(req.body); + console.log('valid', validSig); + */ + if (!validSig) { + res.statusCode = 401; + res.setHeader('Content-Type', 'text/xml'); + res.end('Invalid signature. Are you even Twilio?'); + return; + } + // TODO session via db req.body.CallId req.body.smsId + next(); + }); } }; req.getSiteCapability = function (capname, opts, b, c) { @@ -533,6 +557,8 @@ module.exports.create = function (xconfx, apiFactories, apiDeps) { return function (req, res, next) { cors(req, res, function () { + if (xconfx.debug) { console.log('[api.js] post cors'); } + // Canonical client names // example.com should use api.example.com/api for all requests // sub.example.com/api should resolve to sub.example.com