Unable to signup a new user in Cognito using Javascript - 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.

Related

Cognito - Automatically verifying user on sign up

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);
};

Sequelize update information

I've been struggling with this issue for a day now and can't seem to figure out a way to resolve it. This is the code I'm running
Client side:
const nameInput = document.querySelector("#nameInput");
const urlInput = document.querySelector("#urlInput");
const rowAlert = document.querySelector(".alertAppend");
const divAlert = document.createElement("div");
const nameUpdate = async (e) => {
e.preventDefault();
fetch("/auth/updateName", {
method: 'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: nameInput,
url: urlInput,
})
})
.then(function (data) {
console.log('Request success: ', data);
})
.catch(function (error) {
console.log('Request failure: ', error);
});
};
submitName.addEventListener("click", nameUpdate);
API:
router.get("/updateName", auth, async (req, res) =>{
try {
const { name, url } = req.body;
const ime = name;
const uid = req.session.passport.user;
db.User.find({ where: { id: uid } })
.on('success', function (user) {
if (user) {
user.update({
name: ime,
webhook: url
})
.success(function () {})
}
})
res.json({ message: url});
} catch (err) {
if (err) res.status(500).json({ message: "Internal Error"})
}
});
For some reason it just runs the select query and never proceeds to update the user.
Chrome console output
Debug console output
Sequelize model in case it helps:
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING
}
})
return User;
}
The issue was in the API, it's supposed to be router.post
router.post("/updateName", auth, async (req, res) =>{
const { ime, url } = req.body;
const uid = req.session.passport.user;
console.log(ime);
db.User.findOne({where: {id: uid}})
.then(record => {
let values = {
name: ime,
webhook: url
}
record.update(values).then( updatedRecord => {
console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)
res.status(200).json({ message: "success"});
})
}
})
.catch((error) => {
// do seomthing with the error
throw new Error(error)
})
});
You can try the following code
await db.User.update({
name: ime,
webhook: url
}, { where: { id: uid } });
When defining your model I don't see the webhook field

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.

MongoDB references with Node.js I can not populate

I want to show user's location information on the screen.
For Example:
name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy"
When I call the getuser function I want to display the City and Town name.
This is my code:
UserSCHEMA
// Model for the User
module.exports = (function userSchema() {
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;
var userSchema = new Schema({
name: {
type: String,
require: true
},
surname: {
type: String,
require: true
},
tel: {
type: String,
require: true
},
age: {
type: String,
require: true
},
mevki_id: {
type: String,
require: true
},
lok_id: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'locations'
}]
});
var collectionName = 'users';
var USERSCHEMA = Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA);
return User;
})();
USERController
//This Controller deals with all functionalities of User
function userController() {
var User = require('../models/UserSchema');
// Creating New User
this.createUser = function (req, res, next) {
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var lok_id = req.body.lok_id;
User.create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
lok_id: lok_id
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
//Populateeee
this.getUser = function (req, res, next) {
User.find().populate('lok_id')
.exec(function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'USERS': result
});
}
});
};
return this;
};
module.exports = new UserController();
Location Schema
//Schema for Location
module.exports = (function LocationSchema() {
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;
var LocationSchema = new Schema({
userid: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'users'
},
il: {
type: String,
require: true
},
ilce: {
type: String,
require: true
}
});
var collectionName = 'locations';
var LocationSCHEMA = Mongoose.Schema(schema);
var Location = Mongoose.model(collectionName, LocationSCHEMA);
return Location;
})();
Location Controller
//This Controller deals with all functionalities of Location
function locationController() {
var location = require('../models/LocationSchema');
// Creating New Location
this.createLocation = function (req, res, next) {
var userid = req.params.userid;
var il = req.params.il;
var ilce = req.params.ilce;
location.create({
userid: userid,
il: il,
ilce: ilce
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
// Fetching Details of Location
this.getLocation = function (req, res, next) {
location.find({}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
console.log(result);
return res.send({
'location Details': result
});
}
});
};
return this;
};
module.exports = new locationController();
I already had a problem with model definition.
It was fixed by adding the third parameter to mongoose.model (the explicit collection name)
// Try to replace :
var collectionName = 'users';
var USERSCHEMA=Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA);
// with:
var collectionName = 'users';
var USERSCHEMA=Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA, collectionName);
the collectionName must be set either in the schema definition or in the model definition. for more details see here

NodeJs, Mocha and Mongoose

I have the follow structure:
|server
|db
|mongooseTest.js
|test
|userModel.test.js
|user
|userModel.js
With their code:
mongooseTest.js
var mongoose = require('mongoose');
module.exports = function() {
var db = mongoose.createConnection('localhost', 'dbUnitTest');
db.on('connected', function() {
console.log('DB: ' + db.name + ' local: ' + db.host + ':' + db.port);
});
db.on('error', function(err) {
console.log(err);
});
return db;
};
userModel.test.js
var assert = require('assert'),
should = require('should'),
conn = require('../db/mongooseTest'),
UserModel = require('../user/userModel');
describe('User Model', function() {
describe('Save', function() {
it('Saving...', function() {
var db = conn();
var Model = db.model('User');
var userModel = new Model({
name: 'My Name',
email: 'contact#com.br',
pass: 'anything123'
});
userModel.on('save', function(user) {
console.log('Passed by save event handle from user');
});
userModel.save(function(err, user) {
console.log('Passed by save from user');
if(err) console.log(err);
console.log(user);
});
});
})
})
userModel.js
var mongoose = require('mongoose'),
crypto = require('crypto'),
Schema = mongoose.Schema;
var setPass = function(value) {
var salt = 'anyRandomSaltValue';
this.set('salt', salt);
var pass = hashPass(value + salt);
return pass;
}
var hashPass = function(value) {
return crypto.createHash('sha1').update(value).digest('HEX');
}
var userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
pass: {
type: String,
required: true,
set: setPass
},
salt: {
type: String,
required: true
}
});
userSchema.method({
validatePass: function(senha) {
var salt = this.get('salt');
var passSha = hashPass(senha + salt);
return passSha === this.get('senha');
},
});
userSchema.static({
findByEmail: function(email, success, error) {
this.findOne({
email: email
}, function(e, o) {
if(e) {
if(error) error(e);
} else {
if(success) success(o);
}
});
},
});
module.exports = mongoose.model("User", userSchema);
The problem is...
When I run "mocha" to execute my unit tests, the callback of the save function is not performed.
Thanks for all!
Issue solved with the this approach.
I also found another solution which looks good but I didn'try.

Categories

Resources