the function runs and console.log shows the user object on the backend. I don't understand why it's telling me there is an issue here, and really need some guidance.
vm.register = function() {
//check that passwords match
if(vm.password != vm.passwordRepeat) {
vm.registerError = "Passwords must match.";
return;
} else {
var username = vm.username;
// console.log("Valid form. Checking for existing user",username);
storeDataFactory.userExists(username).then(function(response){
//if user exists, return error
if(response.data.length > 0) {
vm.registerError = "A user with email " + username + " already exists. Please login.";
return;
} else {
//if no user exists
if(response.data.length == 0) {
// console.log("No user exists. Continue with registration.");
}
//assign info to user object
var user = {
username: vm.username,
password: vm.password,
name: vm.name,
phone: vm.phone
};
**storeDataFactory.createUser(user).then(function(response){**
vm.user = response.data;
console.log("Created user", vm.user);
if(response.data.length > 0) {
console.log("Created user", vm.user);
vm.registerMessage = "Successful registration, please login";
vm.registerError = null;
vm.user = response.data;
}
}).catch(function(error){
console.log(error);
vm.registerError = "There was an error creating your account.";
vm.registerMessage = null;
});
}
});
}
};
The backend code:
module.exports.register = function(req, res) {
console.log('registering user', req.body);
//create the user object with hashed pass
User
.create({
username: req.body.username,
name: req.body.name,
phone: req.body.phone,
password: bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10))
}, function(err, user) {
if (err) {
console.log("Error creating account");
res
.status(400)
.json(err);
} else {
console.log("Account created!", user);
res
.status(201)
.json(user);
}
});
};
Account created! and the user object are logged on the backend. It just won't display that damn Successful Registration! Please login. message.
storeDataFactory code:
/* global angular */ angular.module('rumbleApp').factory('storeDataFactory', storeDataFactory);
function storeDataFactory($http) {
return {
userExists: userExists,
createUser: createUser
};
function userExists(username) {
return $http.get('/api/users/userExists/' + username).then(complete).catch(failed);
}
function createUser(user) {
$http.post('/api/users/register', user).then(complete).catch(failed);
}
function complete(response) {
return response;
}
function failed(error) {
console.log(error.statusText);
return "There was an error with the API call.";
}
}
Are you sure you're returning from storeDataFactory.createUser()? Can you post the code for that method?
Sounds like the code is executing, but you're not returning anything from it (hence why it thinks it's undefined)
Related
Please refer to the following image.
I was able to successfully integrate the MFA with my Cognito pool and I am getting the OTP as well. Once the OTP is submitted I get the following error message as a 400 bad request. It seems MFA integration is working since once I entered the wrong code as the OTP then it shows the error message.
Once entered the correct OTP that I received into my mobile only I get this error message. Could someone please help me to sort out this issue?
I am expecting to get rid of this 400 Bad request error message which is returned by cognito endpoint call. Please find the below code for my cognito integration with the ReactJs project.
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log("RESULT SUCCESS: ", result);
const accessToken = result.getAccessToken().getJwtToken();
console.log("ACCESS TOKEN: ", accessToken);
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
// console.log('session validity: ' + session.isValid());
const totpMfaSettings = {
PreferredMfa: true,
Enabled: true
};
cognitoUser.setUserMfaPreference(null, totpMfaSettings, function(
err,
result
) {
if (err) {
console.log(err);
}
console.log("call result " + result);
});
});
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
},
mfaSetup: function(challengeName, challengeParameters) {
console.log("MFA SETUP");
cognitoUser.associateSoftwareToken(this);
},
associateSecretCode: function(secretCode) {
const challengeAnswer = prompt("Please input the TOTP code.", "");
cognitoUser.verifySoftwareToken(
challengeAnswer,
"My TOTP device",
this
);
},
selectMFAType: function(challengeName, challengeParameters) {
var mfaType = prompt("Please select the MFA method.", ""); // valid values for mfaType is "SMS_MFA", "SOFTWARE_TOKEN_MFA"
cognitoUser.sendMFASelectionAnswer(mfaType, this);
},
totpRequired: function(secretCode) {
var challengeAnswer = prompt("Please input the TOTP code.", "");
cognitoUser.sendMFACode(challengeAnswer, this, "SOFTWARE_TOKEN_MFA");
},
mfaRequired: function(codeDeliveryDetails) {
var verificationCode = prompt("Please input verification code", "");
cognitoUser.sendMFACode(verificationCode, this);
},
newPasswordRequired: userAttributes => {
// XXXXXXXX
// This is somethign we need to fetch from an input
cognitoUser.completeNewPasswordChallenge("XXXXXXXX", {}, {
onSuccess: result => {
// login
console.log(result)
}
});
// };
}
});
i'm trying to check if user already exite before register but not work for me
when i test in postman it's still created user any idea ?
create: function (req, res) {
if (req.body.password !== req.body.confirmPassword) {
return res.json(401, {err: 'Password doesn\'t match, What a shame!'});
}
User.find(req.body).exec(function(err,users){
if (err) {
return res.negotiate(err);
}
if (users.length) {
res.status(400);
return res.json('User already exists!');
}
}else{
User.create(req.body).exec(function (err, user) {
if (err) {
return res.json(err.status, {err: err});
}
// If user created successfuly we return user and token as response
if (user) {
// NOTE: payload is { id: user.id}
res.json(200, {user: user, token: jwToken.issue({id: user.id})});
}
});
}
});
try edit your code in this lines
User.find(req.body).exec(function(err,users){});
to :-
User.findOne({email:params.email}).exec(function(err,user){
if(user){
/**
*user exists !
*/
}else{
/**
*create new user
*/
}
}
because you use find with criteria which isn't exist so it's returns
null and create new user in every time
If you want to have users with unique username and/or email you can use unique type in model's attribute definition like this:
attributes: {
username: {
type: 'string',
unique: true
}
}
Then your controller method would look like this:
create: function (req, res) {
if (req.body.password !== req.body.confirmPassword) {
return res.json(401, {err: 'Password doesn\'t match, What a shame!'});
}
User.create(req.body, function (err, user) {
if (err) {
return res.negotiate(err); // validation error will be automatically passed there
}
res.json(200, {user: user, token: jwToken.issue({id: user.id})});
});
});
I have a registration dialog where when the user enters username and password I need to check the DB whether the user is present
or not. But when I am validation for the same my call does not hold back until I get the results from the server.
After searching for a while I got to know about callbacks. So I have added a call back inside this.isUser method.
And it is successful. But now doRegistration method is not synchronous with the isUser method.
How to make all my calls synchronous?
this.doRegistration = function(uname, pwd, confirmPwd) {
if(this.isUser(uname)) {
return "USER_EXISTS";
} else {
saveUser(uname, pwd);
return "SUCCESS";
}
};
this.isUser = function(username) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
return true;
}
}
return false;
});
};
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may rewrite the code like following:
this.doRegistration = function(uname, pwd, confirmPwd, callBack) {
this.isUser(uname,function(flag) {
if(flag){
callBack("USER_EXISTS");
}
else {
saveUser(uname, pwd, function(err,result){
if(err){
callBack("SAVING_FAILED");
}
else {
callBack("SUCCESS");
}
});
}
});
};
this.isUser = function(username,callBack) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
callBack(true);
}
}
callBack(false);
});
};
function saveUser(userName, pwd, callBack){
//code to save user
//chek for error in saving
if(err){
callBack(err,null)
}
else {
callBack(null, "success")
}
}
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may also define saveUser as a function with callback. Here it wont wait for saveUser method to complete.
I want to create an new user in my firebase. This is the code I´m using:
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
logUserIn(email, password);
} else {
$activityIndicator.stopAnimating();
console.log(error.code);
switch (error.code) {
case "INVALID_EMAIL":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "INVALID_PASSWORD":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "EMAIL_TAKEN":
$scope.padding_error = "10";
$scope.error = "Diese E-Mail Adresse ist schon registriert";
$scope.$apply();
}
}
});
}
I want to store the username in addition to email and password somewhere in my firebase. How is this possible instantly after user registration?
If the registration is succesful you can simply push the email and password variables to firebase. See code below.
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
... Registration successful
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
##NEWCODE HERE##
emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email")
passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password")
emailRef.set(email)
passRef.set(password)
logUserIn(email, password);
} else {
... Something went wrong at registration
}
}
});
}
i try to programming a register with express and backbone.js. the express part looks like that
app.post('/signup', function (req, res) {
var name = req.param("name", null);
var country = req.param("country", null);
var email = req.param("email", null);
var cemail = req.param("cemail", null);
var password = req.param("password", null);
if (email !== cemail ||
!validate.Email(email) ||
email == null) {
console.log("There is something wrong with email address");
res.send(400, "Please check your email address.");
return;
};
if (password == null || !validate.Password(password)) {
console.log("There is something wrong with password");
res.send(400, "Password doesn't match security requirements");
return;
};
if (name == null || country == null) {
console.log("Some fields is not filled with value.");
res.send(400);
return;
};
signup(name, country, email, password);
res.send(200);
});
if an user give invalid email address, then it gonna respond with http code 400 and some text. Now my question is, how can i catch up this text, on the backbone.js site. it is possible or not. Frontend backbone.js code
$.post('/signup', {
name: $('input[name=name]').val(),
country: $('input[name=country]').val(),
email: $('input[name=email]').val(),
cemail: $('input[name=cemail]').val(),
password: $('input[name=password]').val()
}, function(data) {
console.log(data);
}).error(function(){
console.log("Sign up error");
});
return false;
the $.post error callback will be passed the response object and that will contain the text error message.
.error(function(response){
console.log("Sign up error", response.responseText);
});