Received invalid response from Lambda: Unrecognized field - javascript

i am working on Amazon lex. when i give input to amazon lex its gives me following error
i add lambda function in Fulfillment and from lambda i am getting customer information from MySQL Database
here is my lambda function
const mysql = require('mysql');
var pool = mysql.createPool({ // a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required
host: process.env.RDS_HOSTNAME,
user: process.env.RDS_USERNAME,
password: process.env.RDS_PASSWORD,
port: process.env.RDS_PORT,
database: process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
let MembershipNumber = event.currentIntent.slots.MembershipNumber;
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
if (err) throw err;
let sql = "select * from Sales.CustomerTable where MembershipNumber= ? LIMIT 1";
let field = [MembershipNumber];
connection.query(sql,field, function (err, result, fields) {
if (err) {
console.log(err); // an error occurred
context.fail(buildResponse(false));
}
else {
if (result.length === 1) {
//console.log(data.Items[0].Arrival_city);
var FirstName = result[0].FirstName;
var LastName = result[0].LastName;
var Address = result[0].Address;
var PrimaryPhone = result[0].PrimaryPhone;
var SecondaryPhone = result[0].SecondaryPhone;
var Email = result[0].Email;
var Type = result[0].Type;
var MembershipNumber = result[0].MembershipNumber;
var Pin = result[0].Pin;
callback(null, {
"dialogAction": {
"type": "ConfirmIntent",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": FirstName,LastName,Address,PrimaryPhone,SecondaryPhone,Email,Type,MembershipNumber,Pin
}
}
});
}
else {
console.log("Membership Number not found");
callback(null, buildResponse(true, "none"));
}
}
});
});
};
function buildResponse(isSuccess, FirstName, LastName, Address, PrimaryPhone, SecondaryPhone, Email, Type, MembershipNumber, Pin) {
if (isSuccess) {
return {
FirstName: FirstName,
LastName: LastName,
Address: Address,
PrimaryPhone: PrimaryPhone,
SecondaryPhone: SecondaryPhone,
Email:Email,
Type:Type,
MembershipNumber:MembershipNumber,
Pin:Pin,
lambdaResult: "success"
};
}
else {
console.log("Lambda returned error to Connect");
return { lambdaResult: "Error" };
}
}
here is the test event object
{
"messageVersion": "1.0",
"invocationSource": "FulfillmentCodeHook",
"userId": "user-1",
"sessionAttributes": {},
"bot": {
"name": "Sales",
"alias": "sales",
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "iamamember",
"slots": {
"MembershipNumber": "78541258"
},
"confirmationStatus": "None"
}
}
i want to integrate this with my contact flow. i don't what is this error about. If anyone of you know help me. Thanks

From the error message, the response JSON from lambda is not matching with what Lex expects. As per the error message, it appears that this line has the problem:
"content": FirstName,LastName,Address,PrimaryPhone,SecondaryPhone,Email,Type,MembershipNumber,Pin
The value of content needs to be a string. However, from your screenshot, this is getting resolved as "content": "alys", "Lastname",...
I believe what you want to do is a concatenation of FirstName, LastName and all the other things you want to return in the content. Use a correct function that will do concatenation of these fields and then put them as comma-separated.
Reference: https://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html

Related

How to make duplicate comparison with MySQL DB information when registering in Node.js

I followed the tutorial with Express, MySQL, and JWT.
And I have confirmed that everything works fine and now I want to check for duplicate emails when I sign up.
I registered both the tutorial source code and the code I tried.
I added the code to check for emails when rows> 0 to check for emails when registering, but after checking with Postman, the duplicate emails are still stored in the DB.
tutorial code
users.post('/register', function(req, res) {
var appData = {
"error": 1,
"data": ""
};
var userData = {
"email": req.body.email,
"password": req.body.password,
}
database.connection.getConnection(function(err, connection) {
if (err) {
appData["error"] = 1;
appData["data"] = "Internal Server Error";
res.status(500).json(appData);
} else {
connection.query('INSERT INTO users SET ?', userData, function(err, rows, fields) {
if (!err) {
appData.error = 0;
appData["data"] = "User registered successfully!";
res.status(201).json(appData);
} else {
appData["data"] = "Error Occured!";
res.status(400).json(appData);
}
});
connection.release();
}
});
});
Trying Code
users.post('/register', function(req, res) {
var appData = {
"error": 1,
"data": ""
};
var userData = {
"email": req.body.email,
"password": req.body.password,
}
database.connection.getConnection(function(err, connection) {
if (err) {
appData["error"] = 1;
appData["data"] = "Internal Server Error";
res.status(500).json(appData);
} else {
connection.query('INSERT INTO users SET ?', userData, function(err, rows, fields) {
if (rows.length > 0) {
if (rows[0].email == email) {
appData.error = 1;
sppData["data"] = "Email Duplicate Error
"
} else {
if (!err) {
appData.error = 0;
appData["data"] = "User registered successfully!";
res.status(201).json(appData);
} else {
appData["data"] = "Error Occured!";
res.status(400).json(appData);
}
}
}
});
connection.release();
}
});
});

Unable to find values stored in Collection, if exist or not,If not exist save in mongodb

code for saving Splunk User data into MongoDb using Node API. I am able to store data in MongoDb but I am facing issue in checking the presence of User data in Db. i.e., i need to check if the user already exists or not, if Yes it should say "User Exists" else it should get added in Database. This is where I got suck and I need help to solve this issue.
.post(function (req, res) {
var db = new mongoOp();
var response = {};
db.find({
'email': req.body.email
}).exec(function (err, data) {
response = {
"error": false,
"message": data
};
if (data) {
alert("user exist");
} else {
db.email = req.body.email;
db.IP = req.body.IP;
db._time = req.body._time;
db.save(function (err) {
if (err) {
response = {
"error": true,
"message": "Error fetching data"
};
} else {
response = {
"error": false,
"message": data
};
}
res.JSON(response);
});
}
});
})

Cannot create user as administrator in AWS Cognito

We have been trying to create users in our Cognito User Pool but keep getting a rather weird error. The stack trace looks as follows:
{
"errorMessage": "Not Found",
"errorType": "UnknownError",
"stackTrace": [
"Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:48:27)",
"Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:105:20)",
"Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:77:10)",
"Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)",
"Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)",
"AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)",
"/var/task/node_modules/aws-sdk/lib/state_machine.js:26:10",
"Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)",
"Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)",
"Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:115:18)"
]
}
Here's our code which is executed in Lambda. The Lambda function itself is invoked by API Gateway without proxy integration.
const AWS = require('aws-sdk');
AWS.config.update({
region: "ap-south-1",
endpoint: "https://dynamodb.ap-south-1.amazonaws.com",
});
const docClient = new AWS.DynamoDB.DocumentClient();
const cispClient = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1'
});
const table = process.env.TABLE_NAME || "User_Info_Test";
exports.newDriverCreated = function (event, context) {
console.log('event: ', event);
// Get username, password
const username = event.username;
const password = event.password;
// Get first and last name
const firstName = event.name;
const lastName = event.family_name;
// Get phone number
const phone = event.phone;
const driverData = {
"TemporaryPassword": password,
"UserAttributes": [
{
"Name": "phone_number",
"Value": phone,
},
{
"Name": "first_name",
"Value": firstName,
},
{
"Name": "family_name",
"Value": lastName,
},
],
"Username": username,
"UserPoolId": 'user-pool-id',
"ValidationData": [
{
"Name": "phone_number",
"Value": phone
}
]
}
cispClient.adminCreateUser(driverData, (err, data) => {
if (err) {
console.error('adminCreateUser error: ', err);
context.done(err);
} else {
console.log('adminCreateUser data: ', data);
context.done(null, data);
}
});
}
The error occurs when we call the adminCreateUser() function. We have absolutely no clue what could be going wrong as we are really new to AWS as a whole.
Any help would be greatly appreciated.
Thanks.
Try mentioning the endpoint when creating the cispClient. It looks like it could be a problem due to an incorrect endpoint. See this and enter link description here. Look here for a list of endpoints.

Firebase security per user

I'm working on a site, using firebase
The security was:
{
"rules": {
"users": {
".read": true,
".write": true
}
}
}
So everyone can add their info, but none can access the main part.
But when someone now types this in the console:
ref = new Firebase("https://xxx.firebaseio.com/users");
ref.createUser({
email: email,
password: password
}, function(error, userData) {});
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {));
ref.remove();
all userdata will be removed.
All users have their own uid (e.g. simplelogin:58) and storageID (e.g. -Js18LFoT0SmFi2Iq4GP)
could I maybe do something with those? I really don't want anyone to be able to remove all of my user data, but I need to let the users edit their own info, and to remove their account when they'd like to.
Here's some of my code:
function register() {
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.createUser({
email: email,
password: password
}, function(error, userData) {
if (error) {
alert("Error creating user: " + error)
} else {
console.log("Successfully created user account with uid:", userData.uid);
var uid = userData.uid
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + uid)
var newUser = usersRef.set({
faveShow1: "",
faveShow2: "",
faveShow3: "",
faveShow4: "",
faveShow5: "",
faveShow6: "",
faveShow7: "",
faveShow8: "",
faveShow9: "",
faveShow10: "",
uid: uid
});
//var key = newUser.key();
//console.log(key)
login();
}
});
}
function login() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {
if (error) {
alert("Login Failed!" + error);
} else {
console.log("Authenticated successfully with payload:", authData);
thisAuthData = authData.uid;
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData);
usersRef.on("value", function(snapshot) {
for (var i = 0; i < 1; i++) {
console.log(snapshot.val())
if (true) {
globalAuthData = snapshot.val();
//globalKey = amount;
var SS = snapshot.val()
show1 = SS.faveShow1;
show2 = SS.faveShow2;
show3 = SS.faveShow3;
show4 = SS.faveShow4;
show5 = SS.faveShow5;
show6 = SS.faveShow6;
show7 = SS.faveShow7;
show8 = SS.faveShow8;
show9 = SS.faveShow9;
show10 = SS.faveShow10;
//...//
}
}
}, function(errorObject) {
alert("The read failed: " + errorObject.code);
});
}
});
}
function removeUser() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
var refSer = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData)
ref.removeUser({
email: email,
password: password
}, function(error) {
if (error === null) {
alert("User removed successfully");
refSer.remove();
logoff();
} else {
console.log("Error removing user:", error);
}
});
}
function edit() {
clear();
var fredNameRef = new Firebase('https://fiery-heat-xxx.firebaseio.com/users/' + thisAuthData);
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
console.log(thisAuthData);
console.log(globalAuthData);
login();
}
};
if (document.getElementById("form1").value != "") {
var show1 = document.getElementById("form1").value;
}
var show2 = document.getElementById("form2").value;
var show3 = document.getElementById("form3").value;
var show4 = document.getElementById("form4").value;
var show5 = document.getElementById("form5").value;
var show6 = document.getElementById("form6").value;
var show7 = document.getElementById("form7").value;
var show8 = document.getElementById("form8").value;
var show9 = document.getElementById("form9").value;
var show10 = document.getElementById("form10").value;
fredNameRef.update({
faveShow1: show1,
faveShow2: show2,
faveShow3: show3,
faveShow4: show4,
faveShow5: show5,
faveShow6: show6,
faveShow7: show7,
faveShow8: show8,
faveShow9: show9,
faveShow10: show10,
}, onComplete);
}
function logoff() {
clear()
var ref = new Firebase('https://fiery-heat-xxx.firebaseio.com/')
ref.unauth();
//...//
}
}
and my securety rules:
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
},
".read": true
}
}
}
But I can't register or update right now...
To make sure a user's information can only be edited by that user, you want to use auth.uid.
https://www.firebase.com/docs/web/guide/understanding-security.html
The most important built-in variable is auth. This variable is
populated after your user authenticates. It contains data about them
and auth.uid, a unique, alphanumeric identifier that works across
providers. The auth variable is the foundation of many rules.
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
}
}
}
}
To make it a little more clear, auth.uid refers to the currently logged in user, and $user_id refers to the location in database. The $ points to the $location rule variable:
https://www.firebase.com/docs/security/api/rule/path.html
{ "rules": {
"users": {
"$user": {
".read": "auth.uid === $user",
".write": "auth.uid === $user"
}
}
}
}
When a user authenticates to a Firebase app, three things happen:
Information about the user is returned in callbacks on the client
device. This allows you to customize your app's user experience for
that specific user.
The user information returned contains a uid (a
unique ID), which is guaranteed to be distinct across all providers,
and to never change for a specific authenticated user. The uid is a
String that contains the name of the provider you're authenticating
with, followed by a colon and a unique id returned from the provider.
The value of the auth variable in your app's Security and Firebase
Rules becomes defined. This variable is null for unauthenticated
users, but for authenticated users it is an object containing the
user's unique (auth.uid) and potentially other data about the user.
This allows you to securely control data access on a per-user basis.

Getting weird "TypeError: object is not a function" in Node, when the object is clearly defined

I'm building a simple server in JavaScript running on the Node.js platform. The server accepts JavaScript Objects, parses them, and executes commands based on what it finds; fairly simple stuff. I call those Objects Envelopes (because you open up envelopes in real life and do things based on what they say. Get it? I'm so clever.).
I have 3 files which are called: server.js, envelope.js, and user-handler.js. In my tests, the user sends a "user" Envelope for the server to parse, eventually so the server creates a new user and adds them into the MongoDB instance I've set up locally.
However, in user-handler.js, I've encountered a weird error: TypeError: object is not a function. I have no idea why I'm getting this error, because the Envelope object is definitely being imported correctly. Below you'll find the 3 files in question. Any and all answers are greatly appreciated!
EDIT: For clarification, here is the exact stacktrace that I get when running a test (which I've also included):
Server listening on port 31337
Accepted input from user...
Opened up the envelope...
[Function: Envelope]
Envelope verified successfully
It's a 'user' command...
Starting to parse the envelope...
Going to create a new user...
Now to save new user...
/home/ME/PROJECT/lib/user-handler.js:52
console.log(new Envelope({
^
TypeError: object is not a function
at Object.module.exports.parseEnvelope (/home/ME/PROJECT/lib/user-handler.js:52:19)
at Envelope.open (/home/ME/PROJECT/lib/envelope.js:34:28)
at Socket.<anonymous> (/home/ME/PROJECT/lib/server.js:22:22)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:720:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:392:10)
at emitReadable (_stream_readable.js:388:5)
at readableAddChunk (_stream_readable.js:150:9)
at Socket.Readable.push (_stream_readable.js:113:10)
server.js
"use strict";
var net = require("net")
, mongoose = require("mongoose")
, dbConf = require("../conf")
, Envelope = require("./envelope")
, UserHandler = require("./user-handler")
, uri, db, server;
uri = (dbConf.uri || "mongodb://localhost") // URI
+ (":" + (dbConf.port || 27017) + "/") // Port
+ (dbConf.db || "DATABASE"); // Database
db = mongoose.connect(uri);
server = net.createServer(function(socket) {
socket.on("data", function(data) {
var input, output;
//try {
input = new Envelope(JSON.parse(data.toString()));
console.log("Accepted input from user...");
output = input.open();
console.log("And the output is: ");
/*} catch (error) {
var errorString = String(error).split(": ");
output = new Envelope({
header: {
type: "error"
},
body: {
errorType: errorString[0],
errorMessage: errorString[1]
}
});
}*/
console.log(JSON.stringify(output));
});
});
server.listen(31337, function() {
console.log("Server listening on port 31337");
});
envelope.js
"use strict";
var userHandler = require("./user-handler");
var Envelope = function Envelope(data) {
for (var key in data) {
this[key] = data[key];
}
};
Envelope.prototype = {
constructor: Envelope,
verify: function() {
console.log(this.constructor);
if (this.header && this.header.type && this.body) {
console.log("Envelope verified successfully");
return true;
} else {
console.log("Envelope did not verify successfully");
return false;
}
},
open: function() {
var self = this;
console.log("Opened up the envelope...");
if (self.verify()) {
switch (self.header.type) {
case "user":
console.log("It's a 'user' command...");
return userHandler.parseEnvelope(self);
break;
default:
return new Envelope({
header: {
type: "empty"
}
});
}
} else {
return new Envelope({
header: {
type: "error"
},
body: {
errorType: "MissingDataError",
errorMessage: "Missing either: header, body, or header.type"
}
});
}
}
};
module.exports = Envelope;
user-handler.js
"use strict";
var User = require("../models/user")
, Envelope = require("./envelope");
module.exports = {
parseEnvelope: function(env) {
var header = env.header;
var body = env.body;
console.log("Starting to parse the envelope...");
switch (header.method) {
case "create":
console.log("Going to create a new user...");
var newName = body.name || {
first: "",
last: ""
};
var newUser = new User({
username: body.username,
password: body.password,
name: newName,
email: body.email || ""
});
console.log("Now to save new user...");
/*newUser.save(function(err) {
if (err) {
console.log("Ruh roh, there was an error...");
console.log(String(err));
} else {
console.log("New user saved successfully to the database...");
return newUser;
}
});*/
/*var response = new Envelope({
header: {
type: "response",
requestType: "user",
requestMethod: "create"
},
body: {
_id: newUser._id,
username: newUser.username,
password: newUser.password,
name: newUser.name,
email: newUser.email
}
});*/
console.log(new Envelope({
test: "Hello, world!"
}));
//console.log(response);
break;
default:
return new Envelope({
header: {
type: "error"
},
body: {
error: "MissingHeaderMethodError",
errorMessage: "Missing header parameter: method"
}
});
break;
}
}
};
tests/user.js
"use strict";
var net = require("net")
, client;
client = net.connect({host: "localhost", port: 31337}, function() {
client.end(JSON.stringify(
{
"header": {
"type": "user",
"method": "create"
},
"body": {
"username": "john_doe",
"password": "password1",
}
}
));
});
The problem is probably that you have circular imports. Your Envelope imports the user-handler and the user-handler import the Envelope. Since the Envelope is "just" an envelope, it problably shoudn't know about the user-handler. So you could refactor it in the following way:
Envelope.js
open: function(callback) {
var self = this;
console.log("Opened up the envelope...");
if (self.verify()) {
switch (self.header.type) {
case "user":
console.log("It's a 'user' command...");
return callback(self);
break;
default:
return new Envelope({
header: {
type: "empty"
}
});
}
} else {
return new Envelope({
header: {
type: "error"
},
body: {
errorType: "MissingDataError",
errorMessage: "Missing either: header, body, or header.type"
}
});
}
}
server.js
output = input.open(UserHandler.parseEnvelope);
Now you don't need to import your user-handler.js in your Envelope.js and everything should work smoothly.

Categories

Resources