Integration with Amplify JS and Cognito in React

Viewed 867

I have been trying the Authentication using Amplify JS and able to log in and Change password when user.challengeName === 'NEW_PASSWORD_REQUIRED' and I have componentDidMount() in my Approuter where all the routes site. when navigated to change password screen componentDidMount() is not calling.

condition in login:

 if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {

     this.props.history.push('/ChangePassword')}

In Approuter:

async componentDidMount() {

    try {
      const session = await Auth.currentSession();
      this.setAuthStatus(true);
      console.log(session);
      const user = await Auth.currentAuthenticatedUser();debugger;
      this.setUser(user);
    } catch(error) {
      if (error !== 'No current user') {
        console.log(error);
      }
    }

change password:

  let user =  Auth.currentAuthenticatedUser();

  Auth.changePassword(
        user, 
        values.tempPassword,              
        values.newPassword

      ).then(user => {
        // at this time the user is logged in if no MFA required
        console.log(user);
      }).catch(e => {
        console.log(e);
      });

Expected:

  1. User has to be Cognito object and change password should update and confirm the user.

Actual:

User.session() is not a function.

1 Answers

I have a sample in Angular (may be same code for React):

cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: result => {
        console.log(err);
        ...
    },
    onFailure: err => {
      console.log(err);
      ...
    },
    newPasswordRequired: (userAttributes, requiredAttributes) => {
      subscriber.error({
        reason: 'FORCE_CHANGE_PASSWORD',
        user: {
          username: user
        }
      });
    }
  });
Related