How to verify JWT in middleware function dialogflow - dialogflow-es

We are sending a HTTP Header with a JWT Token, we have configured this header in dialogflow console.
We want to verify this token in a previous step to send the request to a specific intent, for example welcome_intent.
We are using "middleware" as this previous step, and the verification is correct and it's applied to every communication. And we want to know, how
In case the JWT is wrong, we want to return an error and not continue with the associated intent, for example: welcome_intent.
We have tried to end the flow with "conv.close" in "middleware", but we have seen that the flow continues and it goes to the intent associated with the query.
How can we get out of the flow and return an error in the middleware function?
const {
dialogflow
} = require('actions-on-google');
const fulfillment = dialogflow({
clientId: "clientIdDialogflow",
debug: true
});
const jwt = require('jsonwebtoken');
fulfillment.middleware(async (conv) => {
let tokenIncorrect = await utils.verifyJWT(conv);
if (tokenIncorrect) {
conv.close("Lo siento pero no puedes continuar con la conversación.");
}
});
// Intents functions
fulfillment.intent("welcome_intent", .....);

You should be able to throw an UnauthorizedError to terminate the conversation inside intent handlers.
Here are some relevant docs with some example code: https://actions-on-google.github.io/actions-on-google-nodejs/2.12.0/classes/_service_actionssdk_conversation_conversation_.unauthorizederror.html
However, this won't work from a middleware. As you can see in https://github.com/actions-on-google/actions-on-google-nodejs/blob/9f8c250a385990d28705b3658364c74aa3c19adb/src/service/actionssdk/actionssdk.ts#L345-L350, middleware are applied before the UnauthorizedError handling wrapping the call to the intent handler: https://github.com/actions-on-google/actions-on-google-nodejs/blob/9f8c250a385990d28705b3658364c74aa3c19adb/src/service/actionssdk/actionssdk.ts#L370-L389
As implemented, middleware cannot be used to gracefully end fulfillment directly. You can, however, modify the conv object. For example, you could change the target intent (conv.intent = 'UNAUTHORIZED') in these cases and then add a handler for that intent that always throws an UnauthorizedError.

Related

DialogFlow if statement conv.ask in app.intent

I want to run this code in dialogflow ,basically i want to use if condition
for example.
if my intent "Done" reply response [Text Response] =>'Now add 2 more and say got it' then
it switch to my another intent called "alright" so the response should be "you no. is 1" and end the converstation.
similary
if my intent "Done" reply response [Text Response] =>'Now add 4 more and say got it' then
it switch to my another intent called "alright" so the response should be "you no. is 2" and end the converstation.
and goes on.
just look at the SS Below
enter image description here
enter image description here
'use strict';
// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
var numr=0;
app.intent('done',(conv,output)=>{
if(conv.ask ==='Now add 2 more, and say got it'){
numr=1;
return numr;
}
else{
numr=2;
return numr;
}
});
app.intent('Alright',(conv)=>{
conv.close('your number is '+ numr);
});
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
There are a number of issues with your code that make it difficult to understand exactly what you're doing. However, there are a few things to note. I'm assuming you're using JavaScript here.
You have a syntax error in how you are using else. The else statement should be followed by an execution block. You look like you're following it with a condition. Perhaps you are trying to use else if there?
conv.ask is a function. You're then assigning a string to it which would remove it as a function. I don't think this is what you mean to do here.
In the Intent Handler for the "done" Intent, you're not sending anything back to the user using the conv.ask() function since you just removed that as a function.
Setting a global variable does not guarantee the value of it will be preserved in between Intent Handler calls. If you want a value saved during a conversation, you should use a Context or conv.data or other means.

Google Assistant's fulfillment response comes with escape character "\"

I created a simple webhook to fulfill a Google Action intent using Actions on Google Client Library. This webhook is hosted on an AWS Lambda function with this code:
'use strict';
// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
// Handle the Dialogflow intent named 'favorite color'.
// The intent collects a parameter named 'color'.
app.intent('favorite color', (conv, {color}) => {
const luckyNumber = color.length;
// Respond with the user's lucky number and end the conversation.
conv.close('Your lucky number is ' + luckyNumber);
});
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.fulfillment = app;
My issue is the that the response comes back to the assistant in this form:
{
"statusCode": 200,
"body": "{\"payload\":{\"google\":{\"expectUserResponse\":false,\"richResponse\":{\"items\":[{\"simpleResponse\":{\"textToSpeech\":\"Your lucky number is 3\"}}]}}},\"fulfillmentText\":\"Your lucky number is 3\"}",
"headers": {
"content-type": "application/json;charset=utf-8"
}
}
As you can see, the body comes with the escape letter inserted which causes the fulfillment to fail.
I tried the following:
JSON.stringify(conv.close('Your lucky number is ' + luckyNumber));
JSON.parse(conv.close('Your lucky number is ' + luckyNumber));
JSON.parse(conv.close('Your lucky number is ' + luckyNumber).body);
Nothing changed as I think I need to reach the payload part.
Turns out there's an checkbox option in AWS API Gateway called: Use Lambda Proxy Integration.
When selected it returns the JSON as is from my code without extra formatting.

'Until loop' analogue needed - in order to continue bot dialog - after some status 'marker' is updated

'Until loop' analogue needed to continuously read status variable from helper function - and then (when the status variable is 'as we need it') - to resume bot conversation flow.
In my bot (botbuilder v.3.15) I did the following:
During one of my dialogues I needed to open external url in order
to collect some information from the user through that url.
After that I posted collected data (with conversation ID and other info) from that url to my bot app.js
file
After that I needed to resume my bot conversation
For that I created helper file - helper.js in which 'marker' variable is 'undefined' when the data from url is not yet collected, and 'marker' variable is some 'string' when the data is collected and we can continue our bot conversation
helper.js
var marker;
module.exports = {
checkAddressStatus: function() {
return marker;
},
saveAddressStatus: function(options) {
marker = options.conversation.id;
}
}
I can successfully update variable 'marker' with my data, by calling saveAddressStatus function from app.js.
However, when I get back to writing my code which is related to bot conversation flow (To the place in code after which I opened url - in file address.js, and from where I plan to continuously check the 'marker' variable whether it is already updated - in order to fire 'next()' command and continue with session.endDialogWithResult -> and then -> to further bot conversation flows - I cannot find the equivalent of 'until loop' in Node.js to resume my session in bot dialog - by returning 'next()' and continuing with the bot flow.
address.js
...
lib.dialog('/', [
function (session, args, next) {
...
next();
},
function (session, results, next) {
// Herocard with a link to external url
// My stupid infinite loop code, I tried various options, with promises etc., but it's all not working as I expect it
while (typeof helper.checkAddressStatus() == 'undefined') {
console.log('Undefined marker in address.js while loop')
}
var markerAddress = helper.checkAddressStatus();
console.log(markerAddress);
next(); // THE MOST IMPORTANT PART OF THE CODE - IF markerAddress is not 'undefined' - make another step in dialog flow to end dialog with result
function(session, results) {
...session.endDialogWithResult({markerAddress: markerAddress})
}
...
Any ideas how to make a very simple 'until loop' analoque in this context - work?
Having your bot stop and wait for a response is considered bad practice. If all of your bot instances are stuck waiting for the user to fill out the external form, your app won't be able to process incoming requests. I would at least recommend adding a timeout if you decide to pursue that route.
Instead of triggering your helper class in the endpoint you created, you should send a proactive message to the user to continue the conversation. To do this, you will need to get the conversation reference from the session and encode it in the URL that you send to the user. You can get the conversation reference from the session - session.message.address - and at the very least you will need to encode the bot id, conversation id, and the serviceUrl in the URL. Then when you send the data collected from the user back to the bot, include the conversation reference details for the proactive message. Finally, when your bot receives the data, recreate the conversation reference and send the proactive message to the user.
Here is how your conversation reference should be structured:
const conversationReference = {
bot: {id: req.body.botId },
conversation: {id: req.body.conversationId},
serviceUrl: req.body.serviceUrl
};
Here is an example of sending a proactive message:
function sendProactiveMessage(conversationReference ) {
var msg = new builder.Message().address(conversationReference );
msg.text('Hello, this is a notification');
msg.textLocale('en-US');
bot.send(msg);
}
For more information about sending proactive messages, checkout these samples and this documentation on proactive messages.
Hope this helps!

Error: Can't set headers after they are sent because of res.?

I'm trying to set up a method that is called with Shopify's webhook. I get the data and I'm able to store with a fresh server but I get "Error: Can't set headers after they are sent" returned in the console. I believe this is because I'm calling res twice. Any ideas on how to structure this better?
This is my method:
function createProductsWebHook(req,res,next) {
//if(req.headers){
// res.status(200).send('Got it')
// return next()
// }
res.sendStatus(200)
next()
const productResponse = req.body
console.log(productResponse)
const product = Product.build({
body_html: req.body.body_html,
title: req.body.title,
});
product.save()
.then(saveProduct => res.json(saveProduct))
.catch((e)=> {
console.log(e)
});
}
This occurs because the middleware, createProductsWebHook(), is called first when a request is received, which then sends a 200 status code response, res.sendStatus(200). Then in, in the same middleware function, product.save().then(...) is called. save()’s callback function attempts to send a response too – after one has already been sent by the very same middleware – using res.json(saveProduct).
Key Takeaway
Middleware should not send the response; this defeats the purpose of middleware. Middleware's job is to decorate (add or remove information, i.e, headers, renew some auth session asynchronously, perform side effects, and other tasks) from a request or response and pass it along, like a chain of responsibility, not transmit it – that's what your route handler is for (the one you registered your HTTP path and method with, e.g., app.post(my_path, some_middleware, route_handler).

dialogflow fullfilment and firebase response time

I am trying to build a simple chatbot with DialogFlow.
My aim is to give information from user question, like : where can I slackline above water in croatia ? I have two parameters (croatia, waterline) and a list of slackline places.
So I need a data base to retrieve information from parameters. DialogFlow allows fulfillment with Firebase. I build a database with places (name, country, type of slack) and enable webhook call for my intent.
I use Inline Editor and index.js
const parameters = request.body.queryResult.parameters;
var country = parameters.country.toString();
function show(snap) {
console.log('snap');
agent.add(JSON.stringify(snap.val(),null,2));
}
function slkplc(agent) {
var testRef;
firebase.database().ref('slackplace').once('value',show);
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('slack place', slkplc);
agent.handleRequest(intentMap);
But I do not get the expected result while trying it on DialogFlow or Google Assistant. The function show is asynchronously called but too late and the response is not available for DialogFlow :
I see three way to deal with this problem :
use blocking call to database : another database ?
treat asynchronous message with DialogFlow ???
response to user that an error occured.
The third that I choose, but it is always on error.
After trying several things to wait data from database response, the only thing I managed is to freeze the response, therefore the timeout of DialogFlow - 5s -and Firebase - 60s - were reached.
A workaround
Another way to do it is to separate database acquisition and request/response from DialogFlow. The data of database is collected outside of the dialogflowFirebaseFulfillment
var data;
var inidata = firebase.database().ref().on('value',function(snap) {
console.log('snap');
data = snap.val();
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
...
function slkplc(agent) {
agent.add(JSON.stringify(data,null,2));
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('slack place', slkplc);
agent.handleRequest(intentMap);
}
Now I can do what I want with data, and I am able to find the place where I can practice waterline in croatia. But there is always something weird, the data of the database is duplicated ...
The "right" solution is option 2 that you suggest: since you're doing an asynchronous call, you need to handle this correctly when working with the dialogflow-fulfillment library.
Basically, if your handler makes an asynchronous call, it needs to be asynchronous as well. To indicate to the handleRequest() method that your handler is async, you need to return a Promise object.
Firebase's once() method returns a Promise if you don't pass it a callback function. You can take advantage of this, return that Promise, and also handle what you want it to do as part of a .then() clause. It might look something like this:
function slkplc(agent) {
var testRef;
return firebase.database().ref('slackplace').once('value')
.then( snap => {
var val = snap.val();
return agent.add( JSON.stringify( val, null, 2 ) );
});
}
The important part isn't just that you use a Promise, but also that you return that Promise.

Resources