How to allow my user to reset their password on Cognito User Pools?

Mark Keane picture Mark Keane · Jun 29, 2016 · Viewed 33.4k times · Source

So in my app I obviously want to provide the means for users to reset their passwords. The issue I'm having though is that the new documentation for User Pools is pretty ambiguous on this topic. Here is what they tell you to do for a Forgot Password flow, and the link you may find it at:

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

http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html

However when I drop this code into my project where a cognitoUser is defined and signed in, nothing seems to happen. I understand I need to somehow integrate this code with sending a verification code to the user, and asking them for a new password, but can't find anything on how to do this. Thoughts?

Thanks

Answer

user1322092 picture user1322092 · Jan 23, 2017

AWS' docs are terrible on this topic (Cognito). You basically need to setup cognitoUser, then call forgotPassword

export function resetPassword(username) {
    // const poolData = { UserPoolId: xxxx, ClientId: xxxx };
    // userPool is const userPool = new AWSCognito.CognitoUserPool(poolData);

    // setup cognitoUser first
    cognitoUser = new AWSCognito.CognitoUser({
        Username: username,
        Pool: userPool
    });

    // call forgotPassword on cognitoUser
    cognitoUser.forgotPassword({
        onSuccess: function(result) {
            console.log('call result: ' + result);
        },
        onFailure: function(err) {
            alert(err);
        },
        inputVerificationCode() { // this is optional, and likely won't be implemented as in AWS's example (i.e, prompt to get info)
            var verificationCode = prompt('Please input verification code ', '');
            var newPassword = prompt('Enter new password ', '');
            cognitoUser.confirmPassword(verificationCode, newPassword, this);
        }
    });
}

// confirmPassword can be separately built out as follows...  
export function confirmPassword(username, verificationCode, newPassword) {
    cognitoUser = new AWSCognito.CognitoUser({
        Username: username,
        Pool: userPool
    });

    return new Promise((resolve, reject) => {
        cognitoUser.confirmPassword(verificationCode, newPassword, {
            onFailure(err) {
                reject(err);
            },
            onSuccess() {
                resolve();
            },
        });
    });
}