Handling inbound Twilio messages using node.js - node.js

I'm reading through portions of the Twilio documentation (https://www.twilio.com/help/faq/why-does-my-twilio-number-respond-with-thanks-for-the-message-configure-your-numbers-sms-url-to-change-this-message) pertinent to SMS messaging responses, and am trying to build a node.js app which will allow me to respond to inbound SMS messages with programmatic responses.
I've been trying to emulate this SO post which deals with a similar problem (How can I respond to incoming Twilio calls and SMS messages using node.js?) and have the following code:
var AUTH_TOKEN = "*********************";
var twilio = require('twilio');
var express = require('express');
var http = require('http');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
app.post('/welcome/sms/reply/', function(req, res) {
//Validate that this request really came from Twilio...
if (twilio.validateExpressRequest(req, AUTH_TOKEN)) {
var twiml = new twilio.TwimlResponse();
twiml.say('Hi! Thanks for checking out my app!');
res.type('text/xml');
res.send(twiml.toString());
}
else {
res.send('you are not twilio. Buzz off.');
}
});
http.createServer(app).listen(3000);
Calling the POST request /welcome/sms/reply through a REST client yields the else statement, and I'm not sure why since the AUTH_TOKEN is exactly what I have in my account dashboard.

Twilio developer evangelist here.
If you're trying to call your own endpoint there using a REST client and you are validating requests (twilio.validateExpressRequest) then you will need to construct your request the same as Twilio does. Crucially this includes a X-Twilio-Signature header, read more at that link for more details.
If you test your code with Twilio, it should work and be a valid request.

See this post for reference in incorporating ngrok + Express. https://www.twilio.com/blog/2015/09/monitoring-call-progress-events-with-node-js-and-express.html

Related

Redirect to a https url on server rather than sending 3XX in express

I have a sample http server .
I have a post API which in some scenario have to route to a third party https-server.
Third party server also exposes a post API.
I dont want to send a redirect to client and do this silently on http server.
My application is built using express.
I have tried using request module and tried to use pipe like this .. but request is timing out.
let request = require('request');
console.log(`vishal going here for 300 `);
var pipe = req.pipe(request.post('https url here'));
var response = [];
pipe.on('data', function (chunk) {
response.push(chunk);
});
pipe.on('end', function () {
var res2 = Buffer.concat(response);
console.log(res2);
res.send(res2);
});
Not sure whats missing.
Also how to pass the body and hears to https server request

Get my Action’s server URL in (JavaScript) fulfilment code

I am using actionssdk and I build my Action fulfilments using Javascript and node.js + Express.
I am looking for a way to get the url (protocol + host name + port) of the server where the fulfilment is hosted.
Is there a simple way to do this? E.g. in the MAIN intent? Is there some conv-property I can use? Can I get hold of a req-parameter in the MAIN-intent, from which I can deduct hostname etc?
const express = require('express');
const expressApp = express();
const { actionssdk, ... } = require('actions-on-google');
const app = actionssdk({
ordersv3: true,
clientId: ...
});
expressApp.post('/fulfilment', app);
app.intent('actions.intent.MAIN', (conv) => {
let myUrl: string = ... // ???????
...
});
(background: obviously I know myself to where I deployed my fulfilment code. But I have a reusable template for fulfilment code in which I want to refer to the host url, and I do not want to type that in manually each time I develop a new Action).
You can get access to the request object in a middleware via Framework Metadata which is by default of type BuiltinFrameworkMetadata which contains objects used by Express
For example, you can use it like this, which will be ran before each request:
app.middleware((conv, framework) => {
console.log(framework.express.request.headers.host)
})

NodeJS express framework reads the same event multiple times

I'm working with a service (WSO2CEP) that sends events to a node js program that I developed, let's call it receiver.js, and then it stores these events in a mongo db. The comunication between WSO2CEP and receiver.js is done through a HTTP connection. The problem I'm facing on is that when the WSO2 sends an event, the receiver.js caputres it and stores it in the db, and after a few seconds/minutes, it detects that a new events has arrived, which is not true, and stores it again in the db. This second event is identical to the first one.
When I saw that I thought that the problem was that the WSO2 was sending the same event multiple times, but I've debug it an I'm 100% sure that only one events is being sent, so the problem seems to be the HTTP connection.
The HTTP connection is being handled by the receiver.js acting as a server and WSO2 as a client, which sends the events through HTTP post request. The http server implementation in receiver.js is done with the "express" framework. As it can be seen in below code chunk.
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const EventEmitter = require('events');
const port = Whatever;
module.exports = class WSO2Server extends EventEmitter {
constructor () {
super();
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.route('/Whatever').post( (req, res) => {
let event = req.body;
this.emit('event', event);
});
this.server = app.listen(port);
}
destroy () {
this.server.close();
}
}
I suspect that the events are being stored in a queu (or similar) and are being retransmitted every so often. Any idea about that? Thank you
Looking at your code, I can't see you using the response object at all. After you've called this.emit('event', event); you should call something like res.status(201).end(); which will dispatch a HTTP Status 201 back to the calling client.
Because you're not setting any information on the response object, your application is hanging and not making a response to the HTTP call. Thus something like nginx or apache is re-issuing the request to your application after a specific timeout.
If you explicitly create the response with something res.status(201).end(); then your request will end correctly and a duplicate call will not be made.

Returning 401 error for all routes with hapijs

We're using Hapi JS for our rest server. We store the authentication tokens for the users on Redis. Now, if for some reason node loses connection with Redis, we need to return 401 Authorization failed error to all the clients from all the routes so the clients can logout automatically.
So, is there a way to return 401 from all routes without changing the code in the route handler functions?
You can make use of the Hapi server extension event 'onRequest'.
var hapi = require('hapi');
var Boom = require('boom');
var server = new hapi.Server();
//Configure your server
//Add an extension point
server.ext('onRequest', function (request, reply) {
var status;
//Check status of redis instance
if (status) {
//Redis is running, continue to handler
return reply.continue();
} else {
//Redis is down, reply with error
return reply(Boom.unauthorized('Auth server is down'));
}
});
This is probably not how you will verify the status your redis instance, but I hope you get the point.
One can look up various other extension points here.
You should do this in the auth plugin used by your app. Take a look at the hapi-auth-basic implementation: https://github.com/hapijs/hapi-auth-basic/blob/master/lib/index.js
If you look in the scheme you must define an authenticate method which takes the request and reply. This is where you should check redis for an auth token. If the connection is not available you should
return reply(Boom.unauthorized('Authorization failed', 'Basic'));
Hope this helps.

how to inspect requests response proxied through node.js

I am trying to use node.js to setup a simple proxy server. The idea behind that is to get all web services calls made to one web service go through a node.js proxy in order to easily inspect and debug web service calls.
In order to do that, I am trying to use the following code to proxy the requests:
var
url = require('url'),
http = require('http'),
acceptor = http.createServer().listen(8008);
acceptor.on('request', function(request, response) {
console.log('request ' + request.url);
request.pause();
var options = url.parse(request.url);
options.headers = request.headers;
options.method = request.method;
options.agent = false;
var connector = http.request(options, function(serverResponse) {
serverResponse.pause();
response.writeHeader(serverResponse.statusCode, serverResponse.headers);
serverResponse.pipe(response);
serverResponse.resume();
});
request.pipe(connector);
request.resume();
});
But I can't figure out where to inspect / dump to file the response. With node-inspector, I was looking at the response object at line: serverResponse.pipe(response); but the body of the response is not yet available.
I found the following question node.js proxied request body but it is written in CoffeeScript.
The idea is write your own 'data' handler and don't use pipe().
You cannot eavesdrop on the data once you piped the stream.

Resources