Cognito - Automatically verifying user on sign up - javascript

I am trying to automatically verify users emails when signing them up in my web app which is connected to cognito.
I am using the method to try and do this
adminUpdateUserAttributes
I immediately try to do this after i sign a user up. The user is signed up fine but the users email and phone are not verified in the console
What am i doing wrong in my code?
Here is my code:
$('#signUp').submit(function(event) {
var poolData = {
UserPoolId : '', // your user pool id here
ClientId : '' // your app client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name: 'email',
Value: $('input[name=email]').val(),
};
var dataPhoneNumber = {
Name: 'phone_number',
Value: $('input[name=telephone]').val(),
};
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
console.log(attributeList)
userPool.signUp($('input[name=usernameSignUp]').val(), $('input[name=passwordSignUp]').val(), attributeList, null, function(err, result) {
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
console.log('signed up')
var cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
updateUserAttribute($('input[name=usernameSignUp]').val())
});
//updates the new user to have verified phone and email using adminUpdateUserAttributes() -- this isnt working rn
var cognitoidentityserviceprovider = new AWSCognito.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.adminUpdateUserAttributes({
UserAttributes: [{
Name: 'phone_number_verified',
Value: 'true'
}, {
Name: 'email_verified',
Value: 'true'
}
],
UserPoolId: '',
Username: $('input[name=usernameSignUp]').val()
}, function(err) {
if (err) {
console.log(err, err.stack)
} else {
console.log('Success!')
}
})
});```

For your usecase you should allow autoVerify when signing up.
This is done in a presignup lambda.
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
You should create a presignup lambda similar like this:
exports.handler = (event, context, callback) => {
event.response.autoConfirmUser = true;
event.response.autoVerifyEmail = true;
event.response.autoVerifyPhone = true;
callback(null, event);
};

Related

Node JS Imap-simple disconnect error after some time

I fetch unread messages in a middle ware that triggers my function every five minutes. It is successfully completing the request but eventually It triggers and crashes my nodejs process. With an error of:
Error: This socket has been ended by the other party
I have tried adding all these catches and error handling but It seams it eventually times out my connection to my inbox? Am I not reconnecting on every request to access my inbox?
Here is my code (also I have tried with authTimeout: 3000 in the config before anyone suggests that is the issue):
imap: {
user: 'myemail#gmail.com',
password: 'myPW',
host: 'imap.gmail.com',
port: 993,
tls: true,
keepalive: true
}
imaps.connect(settings.emailConfig).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['UNSEEN'];//only grab unread messages in LTS email
var fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
markSeen: true//mark as read
};
return connection.search(searchCriteria, fetchOptions).then(function (messages) {
console.log('looking for unread messages')
if (messages.length > 0) {
console.log('unread messages to save')
console.log('looking at messages : ' + util.inspect(messages, { depth: null }))
var saveUnreadEmais = messages.map(function (item) {//resolve each promise of unread message
var all = _.find(item.parts, { "which": "" })
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
simpleParser(idHeader + all.body, (err, mail) => {
var BarCode = "";
var subject = mail.subject;
var to = mail.to.value[0].address;
var from = mail.from.value[0].address;
var text = mail.text;
if (mail.subject.includes('Barcode :')) {//if the message to the system includes BarCode in the subject line grab it
var split = mail.subject.split(':');
BarCode = split[1];
}
if (!subject) {
subject = "LTS Email Recieved - Barcode : " + BarCode;
}
if (!text) {
text = "LTS auto email"
}
var newrec = {};
newrec.MessageDate = new Date();
newrec.MessageFor = to;
newrec.MessageFrom = from;
newrec.Message = text;
newrec.MessageAbout = BarCode;
newrec.MessageSubject = subject;
newrec.MessageStatusCode = 1;//1 sent, 2 read, 3 saved, -1 deleted
//console.log('saving message with details of : ' + util.inspect(newrec, { depth: null }))
return db.knex('dbo.PersonnelMessages').insert(newrec).then((data) => {
return "sent";
});
});
});
return Promise.all(saveUnreadEmais).then(() => {
//do anything you want after saving all unred emails to our db.
}).catch((err) => { console.log("error : " + err) })
}
else {
console.log('no new emails')
}
}).catch((err) => { console.log("error : " + err) })
}).catch((err) => { console.log("opening inbox error : " + err) })
}).then(function () {
console.log('In the INBOX');
}).catch(function (e) {
console.log('error : ' + e);
});

Unable to signup a new user in Cognito using Javascript

I'm trying to signup/login users using Amazon Cognito. I've created a userpool in Cognito and using Javascript to get user details. But the function userPool.signup gives error code "Network error".
The Javascript code:
var login_form = new Vue({
el: '#sign',
data: {
formOpen: false,
v_name: '',
v_email: '',
v_mobile: '',
v_password: '',
productData: {
title: 'HI',
rating: '',
price: '',
list_price: '',
is_featured: false
}
},
methods: {
resetForm: function () {
this.productData = {
title: '',
rating: '',
price: '',
list_price: '',
is_featured: false
}
},
signup: function () {
try {
var poolData = {
UserPoolId: 'us-east-1_fKUK4frdl',
ClientId: '6jsaiafnffqd7bufnrq1mdb1nm'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var username = this.v_email;
var password = this.v_password;
var attributeList = [];
var dataEmail = {
Name: 'email',
Value: this.v_email
};
var dataPhoneNumber = {
Name: 'phone_number',
Value: this.v_mobile
};
var dataName = {
Name: 'name',
Value: this.v_name
}
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber);
var attributeName = new AmazonCognitoIdentity.CognitoUserAttribute(dataName);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
attributeList.push(attributeName);
var cognitoUser;
console.log("username:" + username);
console.log("password:" + password);
console.log("attributes:" + attributeList);
userPool.signUp(username, password, attributeList, null, function (err, result) {
if (err) {
console.log(err);
console.log("Error here");
alert(err);
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
});
} catch (err) {
console.log(err);
alert("Exception error");
}
},
cancel: function () {
this.formOpen = false;
this.resetForm();
},
mounted() {
console.log("Sign app mounted");
}
}
})
The console output is as follows:
username:tempmail#mail.com ecommerce-main.js:193
password:temppassword#123 ecommerce-main.js:194
attributes:{"Name":"email","Value":"tempmail#mail.com"},{"Name":"phone_number","Value":"+919994443322"},{"Name":"name","Value":"Balaji"} ecommerce-main.js:198
{code: "NetworkError", name: "Error", message: "Network error"} ecommerce-main.js:199
Error here
As suggested by a user in github, I've tried changing the Attribute settings in UserPool leaving everything unchecked in Username option. Yet, the same error persists. Please suggest a solution.

InvalidParameterType: Expected params.UserAttributes Name to be a string AWS Cognito SDK

I am totally new to aws cognito sdk. I am trying to sign up a user using cognito sdk in Node.js. Whenever I try to run the node.js code, It throws me an error saying
{ MultipleValidationErrors: There were 5 validation errors:
* InvalidParameterType: Expected params.UserAttributes[0].Name to be a string
* InvalidParameterType: Expected params.UserAttributes[1].Name to be a string
* InvalidParameterType: Expected params.UserAttributes[2].Name to be a string
* InvalidParameterType: Expected params.UserAttributes[3].Name to be a string
* InvalidParameterType: Expected params.UserAttributes[4].Name to be a string
Here is my code.
index.js
var AWSCognito = require('aws-sdk');
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var CognitoSDK = require('amazon-cognito-identity-js-node');
AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool = CognitoSDK.CognitoUserPool;
AWSCognito.CognitoIdentityServiceProvider.CognitoUser = CognitoSDK.CognitoUser;
AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute = CognitoSDK.CognitoUserAttribute;
AWSCognito.config.region = 'us-west-2';
var poolData = {
UserPoolId : '...', // your user pool id here
ClientId : '....' // your app client id here
};
var userPool =
new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'jayanthv', // your username here
Pool : userPool
};
//---------------Signing up Users for Your App---------------------
var attributeList = [];
var dataEmail = {
Name : JSON.stringify("email"),
Value : 'jayanth49#gmail.com' // your email here
};
var dataPhoneNumber = {
Name : 'phone_number',
Value : '8326623393' // your phone number here with +country code and no delimiters in front
};
var dataName = {
Name : 'name',
Value : 'Jayanth' // your phone number here with +country code and no delimiters in front
};
var dataProfile = {
Name : 'profile',
Value : 'SamplePortal' // your phone number here with +country code and no delimiters in front
};
var dataGender = {
Name : 'gender',
Value : 'Male' // your phone number here with +country code and no delimiters in front
};
var attributeEmail =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
var attributePhoneNumber =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber);
var attributeName =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataName);
var attributeProfile =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataProfile);
var attributeGender =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataGender);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
attributeList.push(attributeName);
attributeList.push(attributeProfile);
attributeList.push(attributeGender);
var cognitoUser;
userPool.signUp('jayanthv', 'J#asdada', attributeList, null, function(err, result){
if (err) {
console.log(err);
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
});
I don't really have any idea why this occurs. I have searched a lot in aws forums and stack overflow. I would be happy if anyone can help me solve this issue.
---UPDATED CODE---
Followed the below documentation which explains in detail how to use the API calls.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html
Here is my updated code.
index.js
var AWSCognito = require('aws-sdk');
AWSCognito.config.region = 'us-west-2';
exports.handler = (event, context, callback) => {
var params = {
ClientId: event.ClientId, /* required */
Password: event.Password, /* required */
Username: event.Username, /* required */
UserAttributes: [
{
Name: 'email', /* required */
Value: event.email
},
{
Name: 'gender',
Value: event.gender
},
{
Name: 'name',
Value: event.name
},
{
Name: 'phone_number',
Value: event.phone_number
},
{
Name: 'profile',
Value: event.profile
}
/* more attributes if needed */
]
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider();
var responseData = null;
userPool.signUp(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data);
responseData = data;
}
// successful response
});
console.log(responseData);
callback(responseData, null );
};
The above code is written and tested in a Lambda Function.
This is how it worked for us,
//Required parameters in event:
var event = {};
event.params = {
ClientId: 'clientid', /* required */
Password: 'password', /* required */
Username: 'username', /* required */
UserAttributes: [
{
Name: 'email', /* required */
Value: 'emailaddress'
},
{
Name: 'family_name',
Value: 'familyname'
},
{
Name: 'given_name',
Value: 'givenname'
},
{
Name: 'phone_number',
Value: '+19999999999'
}
/* more attributed if needed */
]
};
// Above event is for reference
exports.Execute = function(event, callback) {
var params = event.params;
cognitoidentityserviceprovider.signUp(params, function(err, data) {
if (err) {
callback(null, err);
} else {
callback(null, data);
}
});
I had to remove some of the application specific code, that is not related here.
Hope it helps.

how to access variables inside app.get

How can I access a variable or set of variables inside app.get and make it accessible to the whole project? I am trying to capture the information sent from the SMS text, organized into the "messageData" variable, then sent to the "MessageSchema," where it is then sent and stored in the Mongo Database. My issue is that I believe none of the variables(message, number, answer) are truly being found. How can I fix that?
app.js
app.get('/smssent', function(req, res, callback) {
var message = req.query.Body;
var number = req.query.From;
var twilioNumber = req.query.To;
var context = null;
var index = 0;
var contextIndex = 0;
contexts.forEach(function(value)
{
console.log(value.from);
if (value.from == number)
{
context = value.context;
contextIndex = index;
}
index = index + 1;
});
console.log('Recieved message from ' + number + ' saying \'' + message + '\'');
var conversation = new ConversationV1({
username: '',
password: '',
version_date: ConversationV1.VERSION_DATE_2016_09_20
});
//console.log(JSON.stringify(context));
//console.log(contexts.length);
conversation.message({
input: { text: message },
workspace_id: '',
context: context
}, function(err, response) {
if (err) {
console.error(err);
} else {
var answer = response.output.text[0];
if (context == null) {
contexts.push({'from': number, 'context': response.context});
} else {
contexts[contextIndex].context = response.context;
}
var intent = response.intents[0].intent;
console.log(intent);
if (intent == "done") {
//contexts.splice(contexts.indexOf({'from': number, 'context': response.context}),1);
contexts.splice(contextIndex,1);
// Call REST API here (order pizza, etc.)
}
var client = require('twilio')(
'',
''
);
client.messages.create({
from: twilioNumber,
to: number,
body: response.output.text[0]
}, function(err, message) {
if(err) {
console.error(err.message);
}
});
}
});
res.send('');
});
(ABOVE)This is what retrieves the SMS text, and conducts Twilio, Node, and IBM Bluemix.
index.js
router.post('/app', function(req, res, next) {
if (req.body.number &&
req.body.message &&
req.body.answer
) {
// create object with form input
var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
// use schema's `create` method to insert document into Mongo
Message.create(messageData, function (error, message) {
if (error) {
return next(error);
} else {
return res.redirect('/');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
});
(ABOVE)This is the code to organize and prepare everything for the "MessageSchema."
message.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var MessageSchema = new mongoose.Schema({
number: {
type: String,
required: true,
trim: true
},
message: {
type: String,
required: true,
trim: true
},
answer: {
type: String,
required: true,
trim: true
}
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
Finally, this is what sends all the info to the DB.
If anyone finds anything or has any tips to improve this code, please let me know, I am open for all the input you can give me!
THANKS!
var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
This is OK. However, keep in mind that these variables are sent through POST body, not queries like the other one.
queries: ?param = ...
body: (like POST form; hidden from the URL)
If you unsure whether you are passing them alright, you can test that easily by console.info(...) on a certain point; and using Postman to easily test POST behavior.

return resolve error in node function

Why wont usernametoid function return the acual id? cause im trying to send the result of the userdata as the return. In this case, i want to only send the userdata`s _id attribute. but it seems like it wont work.
console.log(userdata._id); // works
return resolve(userdata._id); // wont work.
output of variable userdata:
{
cash: 7300002,
bank: 0,
xp: 0,
rank: 1,
points: 1,
location: 1,
health: 100,
protection: 1,
attack: 1,
family: '0',
password: 'jKa4qC7pRCgE5jvzD9Vv1pRUNxFlQEM7Jpq/IoJ/sUWOAv1Wx1RI/j/Vu6Zf8zyNkCFcg3QBtdfAC+lmPS8KIA==',
profileImageURL: 'modules/users/client/img/profile/default.png',
roles: [ 'user' ],
created: Sat Aug 27 2016 12:33:55 GMT-0400 (EDT),
__v: 0,
username: 'signature',
provider: 'local',
salt: '4ySlrr9ggESxBB3dR5bx4Q==',
_id: 57c1c0f3b6b20c011242bf22 }
when i do: `return resolve(userdata._id) it would get this error:
/server/factory/user_factory.js:52
return resolve(userdata._id);
^
TypeError: Cannot read property '_id' of null
node.js call:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
var userFunc = require('../factory/user_factory.js');
app.post('/api/kill', function (req, res) {
console.log("starting");
var username = "signature";//req.query.username;
var result = ["test service"];
var data = req.user;
userFunc.usernametoid(username).then( function (otherplayerid) {
if (!(otherplayerid)) {
console.log("other player is acually " + otherplayerid);
result.push("denne brukeren finnes ikke! " + otherplayerid);
} else {
userFunc.usernametoid(otherplayerid).then( function (otherplayer) {
if (data.location != otherplayer.location) {
result.push("Du er ikke i samme lokasjon som " + username);
result.push(data.location + " vs " + otherplayer.location);
} else {
userFunc.addCash(req.user._id,100000);
result.push("starter lokasjonisering");
}
});
}
res.json(result);
});
});
user factory:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
exports.usernametoid = usernametoid;
function usernametoid(id) {
return new Promise( function (resolve, reject) {
var query = Users.findOne( { username : id } );
// var query = Users.find({_id:id});
query.exec(function(err, userdata) {
if (err){
return reject({err : 'Error while getting user info'});
}
console.log(userdata._id);
return resolve(userdata);
});
}, function (){
return reject({err : 'error while fetching cash'});
});
}
Because you are not passing correctly the fetched user to the query.exec.
You need to do:
var Users = require('../models/users-model.js');
function usernametoid(id) {
return new Promise( function (resolve, reject) {
Users.findOne({ username : id }).then( function(user){
//If you use lodash you can do _.isNull(user)
if(user == null){
return reject({error : 'User not found'});
}
user.exec(function(userdata, error) {
if(userdata){
return resolve(userdata);
}
if(error){
return reject({error : 'Error while executing query'});
}
});
});
});
}
I don't really get why you are importing Users Model like that. I do not think Node will be able to fetch it like that.
And, you should require mongoose in your server.js
To catch the rejection you need the following code:
UserFactory.userNameToId(id).then( function(response){
if(response.error){
console.log('error '+response.error);
}
if(response){
console.log('Got response '+response);
}
});

Categories

Resources