typescriptamazon-web-servicesamazon-cognitoaws-userpools

How to implement forgot password route typescript AWS Cognito Userpool?


I have a typescript project setup with AWS cognito. I have created a test userpool and have successfully been able to implement routes for login, register, confirm-account. Currently, I am working on a forgot-password route. The code for which is below. When I test this code, I get the following error message Contact administrator to reset password. Is it possible to create this route so that a confirmed user may directly view their password or perhaps even reset their password?

import AmazonCognitoIdentity from 'amazon-cognito-identity-js';

const UserPoolId = ************;
const ClientId = ************;
const region = ************

const config = {region: region }

export const resetPassword = async (req, res) => {
    try {
        const { username } = req.body;

        const poolData = {
            UserPoolId: ************,
            ClientId: ************,
          };
          
        const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

        const userData = {
            Username: username,
            Pool: userPool,
          };

        const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

        
        cognitoUser.forgotPassword({
            onSuccess: (data) => {
                console.log(data)
                res.status(200).json({ message: "Password Reset"});
            },
            onFailure: (err) => {
                console.log('ERR:', err)
                res.status(401).json({ message: "Password Not Reset", error: err.message});
            },
        })
    }
    catch (err) {
        console.log("FAILED")
        console.log("Error"+ err.message)
        res.status(500).json({ message: "Password Not Reset", error: err.message});
    }
  };

The flow that I have in mind is that if this route is selected, the user could either directly reset their password, or they could get a confirmation email with a code to confirm their account and in doing so, they could obtain a new passowrd. Does this flow exist in AWS Cognito User Pools?

Any assistance would be much appreciated!


Solution

  • This implementation ended up being correct. The issue was that messaging was not configured properly in the AWS Cognito UI. For future reference, User Pools -> User Pool -> Messaging -> Email must be edited to allow for emails to be sent with password reset codes.