I'm doing my app users management with the Cognito AmazonWebService and on AngularJS.
I can not figure out how to solve this problem :
After registering, users are receiving an email with a code to confirm it. When I try to enter and validate the code I have a pop-up message saying "Error: the user is not authenticated".
But if is I swap the steps I can not authenticated myself because I've this error: "Your account must be confirmed".
EDIT: That's how I'm confirming the registration :
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
var userData = {
Username : username,
Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.getAttributeVerificationCode('email', {
onSuccess: function (result) {
console.log('call result: ' + result);
},
onFailure: function(err) {
console.log("error");
alert(err);
},
inputVerificationCode: function(code) {
var verificationCode = prompt('Check you email for a verification code and enter it here: ' ,'');
cognitoUser.verifyAttribute('email', verificationCode, this);
}
});
I have also try this code below :
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.confirmRegistration('123456', true, function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});
But everytime I'm using the code you gave me to confirm an user I have this error message : "ExpiredCodeException: Invalid code provided, please request a code again." while user is well confirmed in my user pool...
How could I solve it ?
Your second code is the right one to be called. How long are you waiting to call?
Related
I am trying to make a custom authentication flow using AWS Cognito so that i can send MFA codes via email instead through the cognito triggers. I am using the initiateAuth() method to do this which is correct according to the documentation;
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#initiateAuth-property
My payload seems to be valid but when i try login with a user i get the error 't.getauthparameters is not a function'
I've had a look through some other stackoverflow posts but nothing is helping
Any ideas what is going wrong?
This is a snippet from my code below:
const payload = {
AuthFlow: 'CUSTOM_AUTH',
ClientId: 'my client id',
AuthParameters: {
USERNAME: $('input[name=username]').val(),
PASSWORD: $('input[name=password]').val(),
CHALLENGE_NAME: 'SRP_A'
}
};
cognitoUser.initiateAuth(payload, {
onSuccess: function(result) {
// User authentication was successful
},
onFailure: function(err) {
// User authentication was not successful
},
customChallenge: function(challengeParameters) {
// User authentication depends on challenge response
var verificationCode = prompt('Please input OTP code' ,'');
cognitoUser.sendCustomChallengeAnswer(verificationCode, this);
},
});
So i ended up finding out that initiateAuth() is not the correct method to use.
The right method to use is cognitoUser.authenticateUser() (since i am using SRP-based authentication then adding a custom challenge) - My updated code is below
This was a similar example that i followed to help me find the answer
I couldnt find very much online for doing it with just the Amazon Cognito Identity SDK so hopefully this is helpful for anyone doing the same!
AWSCognito.config.region = 'region';
var poolData = {
UserPoolId : 'user pool id',
ClientId : 'client id'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: $('input[name=username]').val(),
Pool: userPool,
};
var authenticationData = {
Username : $('input[name=username]').val(),
Password : $('input[name=password]').val(),
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.setAuthenticationFlowType('CUSTOM_AUTH');
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('success');
var resultStr = 'Login Successful';
console.log(resultStr);
$('#resultsSignIn').html(resultStr);
},
onFailure: function(err) {
alert(err);
},
customChallenge: function(challengeParameters) {
// User authentication depends on challenge response
var verificationCode = prompt('Please input OTP code' ,'');
cognitoUser.sendCustomChallengeAnswer(verificationCode, this);
},
});
return false;`
A downside to the authenticateUser() method is that you won't be able to get user's input mid-execution during the authenticateUser workflow (i.e, having to use prompts in the callbacks for customchallenge etc). I believe initiateAuth() would solve this issue.
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html
If I click the "reset password" button for a user in the AWS Cognito, all it does is re-send the verification email, containing the account registration email code.
However, if the user takes that code and enters it on the verification page, AWS returns the error:
NotAuthorizedException: User cannot be confirmed. Current status is RESET_REQUIRED
First, how do I get Cognito to send a real "password reset" email instead of the "confirm your registration" email?
I assume it's giving me this error because the verification JS is calling:
createCognitoUser(email).confirmRegistration(code, true, function confirmCallback(err, result)
and not some undocumented password reset function. What function should I be calling?
You should be calling forgotPassword. From the AWS Documentation at Using Amazon Cognito User Identity Pools Javascript Examples:
cognitoUser.forgotPassword({
onSuccess: function (result) {
console.log('call result: ' + result);
},
onFailure: function(err) {
alert(err);
},
inputVerificationCode() {
var verificationCode = prompt('Please input verification code ' ,'');
var newPassword = prompt('Enter new password ' ,'');
cognitoUser.confirmPassword(verificationCode, newPassword, this);
}
});
So Even I faced a same issue, Even in AWS cognito documentation it was not clear, basically the process involves two steps.
call cognitoUser.forgotPassword() this will start forgot password process flow, and the user will receive a verification code.
then call cognitoUser.confirmPassword() which will reset the password verifying the code send to the email of user.
Below I have given a cognitoUserClass which has static methods forgotPassword() and confirmPassword() methods which implements those two steps.
import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js'
class cognitoUserClass {
static cognitouser: AmazonCognitoIdentity.CognitoUser
static userPool = new AmazonCognitoIdentity.CognitoUserPool({
UserPoolId: 'your pool id',
ClientId: 'your client id',
})
static forgotPassword(userName: string): void {
const userData = {
Username: userName,
Pool: cognitoUserClass.userPool,
}
cognitoUserClass.cognitouser = new AmazonCognitoIdentity.CognitoUser(
userData
)
cognitoUserClass.cognitouser.forgotPassword({
onSuccess: (data) => {
console.log(data)
},
onFailure: (err) => {
console.log('ERR:', err)
},
})
}
static confirmPassword(
verificationCode: string,
newPassword: string
): void {
cognitoUserClass.cognitouser.confirmPassword(
verificationCode,
newPassword,
{
onFailure(err) {
console.log(err)
},
onSuccess(data) {
console.log(data)
},
}
)
}
}
export { cognitoUserClass }
I am making a chat application which requires users to log in, I have so far managed to get the login system working by using UserApp.io, but I cant seem to find a way which would send a "Callback" back to the user who has emited the information to the server.
So for index.html, when a login form is submitted, it would gather the values of the two fields and emit the data to the backend.
$('form#login').submit(function() {
var data = {};
data.email = $("#login_email").val();
data.password = $("#login_password").val();
socket.emit('user login', data);
});
In the index.js file, it receives the details and checks using the UserApp API that the user is valid and all the details are correct. It also retrieves information like the first and last name.
socket.on('user login', function (user) {
logger.info('Receiving login info for "' + user.email + '"...');
UserApp.User.login({"login": user.email, "password": user.password}, function (error, result) {
if (error) {
logger.error('Login failed: ' + error.message);
} else {
var userToken = result.token;
var userID = result.user_id;
console.log("User has logged in.");
UserApp.User.get({
"user_id": userID
}, function (error, result) {
if (error) {
logger.error(error.message);
} else {
logger.info(result[0]['first_name'] + " " + result[0]['last_name'] + " Has logged in!")
}
});
}
});
});
So here is my issue. I cant seem to find a way of giving a callback to index.html so it can show errors like "Incorrect username".
So is there a way of giving a callback to one person, more specificly, the person who submitted the login form?
Any help would be appreciated.
Thanks.
socket.io has acknowledgement callbacks, here are the docs
http://socket.io/docs/#sending-and-getting-data-(acknowledgements)
Add a callback function as the third argument when emitting
$('form#login').submit(function() {
var data = {};
data.email = $("#login_email").val();
data.password = $("#login_password").val();
socket.emit('user login', data, function (result) {
console.log(result);
});
});
and then the callback function server side can have an additional parameter which is the callback you defined when emitting
socket.on('user login', function (user, callback) {
logger.info('Receiving login info for "' + user.email + '"...');
UserApp.User.login({"login": user.email, "password": user.password}, function (error, result) {
if (error) {
logger.error('Login failed: ' + error.message);
} else {
var userToken = result.token;
var userID = result.user_id;
console.log("User has logged in.");
UserApp.User.get({
"user_id": userID
}, function (error, result) {
if (error) {
logger.error(error.message);
} else {
logger.info(result[0]['first_name'] + " " + result[0]['last_name'] + " Has logged in!")
return callback('your results');
}
});
}
});
});
I am using parse javascript SDK, but when I try to handle user registration errors, such like username already taken, the error callback is not triggered.
The code I have is:
signUp: function () {
var self = this;
var errors = this.form.commit({ validate: true });
if(errors) return;
mainapp.showSpinner();
this.model.signUp({
success: function (user) {
console.log(user);
},
error: function (user, error) {
//mainapp.hideSpinner();
console.log('called')
self.errorMessage.html(error);
}
});
},
And the console.log('called) is not triggered, but in console of Chrome I have an javascript error POST https://api.parse.com/1/users 400 (Bad Request)
Any idea how can i catch and handle the error in the error callback?
By checking at the Parse JS sdk documentation, it seems like you miss one parameter when calling sign up function :
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
https://parse.com/docs/js/guide#users-signing-up
Hope this could help to solve your problem.
I'm trying to use Parse.com to sign users up to my application I'm developing. However I seem to get an error when firing my function.
Parse.initialize("APP ID", "JS KEY");
function signUp() {
var user = new Parse.User();
// Get user inputs from form.
var username = document.login.username.value;
var password = document.login.password.value;
user.set("username", username);
user.set("password", password);
user.signUp(null, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
};
The error:
Error: 100 XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
Any help here would be great, i'm unsure what's causing the error. Seems to work correctly when i'm not passing form data through it. Thanks.
I think you instead should use:
user.setUsername(username);
user.setPassword(password);
Also, these can be combined:
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});