I have used aws-cognito in node js
and angular2
.
When you attempt first time login then user injects the temporary credentials, after this an OTP will be sent to either phone or email ( decided by user pool ).
The following is function used for login:
var authenticationData = {
Username: username, // req.body.username
Password: password // req.body.password
};
var poolData = {
UserPoolId: upid,
ClientId: cid,
AuthFlow: 'ADMIN_NO_SRP_AUTH'
};
var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var userData = {
Username: username,
Pool: userPool
};
var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// not for first time login case and user has permanent credentials
},
onFailure: function (err) {
res.send(err); //login failure
},
newPasswordRequired: function (userAttributes, requiredAttributes) {
response = {"ChallengeName": "NEW_PASSWORD_REQUIRED", "userAttributes": userAttributes};
localStorage.setItem('userAttributes', JSON.stringify(userAttributes)); // I have used localStorage to save data temporarily
res.send(response);
}
}
Now, as you are asking for first time login.
So you need to pass the old password and username, user attributes to next API call to get the permanent credentials.
I have not sent token in email message
and keep that in localStorage
so that can be utilised when user come back to the browser this way you will get the ID Token.
so you can use the code for update password as follows:
router.post('/updatepassword', function (req, res) {
var username = req.body.username;
var newPassword = req.body.newpassword;
var userAttributes = req.body.userAttributes;
var oldpassword = req.body.oldpassword;
var userPool = globalConfiguration(); // custom function to get pool data
var userData = {
Username: username, //req.body.username,
Pool: userPool
};
var params = {
UserPoolId: 'us-west-2_XxxxxXX', /* required */
Username: username, //req.body.username,
};
var authenticationData = {
Username: username, //req.body.username,
Password: oldpassword, //req.body.password,
};
var authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
// so only username and previous password are required.
var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) { },
onFailure: function (err) { },
newPasswordRequired: function (userAttributes, requiredAttributes) {
// the api doesn't accept this field back
delete userAttributes.email_verified;
delete userAttributes.phone_number_verified;
cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
var success = {'success': 'success'};
res.send(success);
}
});
});
Hope this will helps you!