ReactJS / AWS Cognito在执行中获取用户输入

时间:2017-09-28 15:21:05

标签: javascript reactjs amazon-web-services amazon-cognito aws-cognito

我有一个使用React构建的简单登录页面,该页面使用AWS Cognito API对用户进行身份验证。有一些身份验证方案(密码需要更新,需要输入MFA代码等),这些方案要求我在执行 authenticateUser 工作流程时获得用户输入。我试图找到一种方法来动态获取用户输入而不使用内置的prompt()方法,尤其是当用户输入新密码时。根据 authenticateUser 工作流程的结构,我试图在工作流程中获取所有用户输入。

也许我没有以正确的方式思考这个问题,但我怎样才能动态渲染另一个React组件,获取用户输入(新密码,MFA代码等),然后使用它在authenticateUser工作流程中输入?

主要的Login组件有一个表单,单击Submit按钮后会触发以下功能:

handleSubmit = async (event) => {
    event.preventDefault();

    this.setState({ isLoading: true, loginError: null });

    try {
      await this.login(this.state.username, this.state.password);
      this.props.userHasAuthenticated(true);
    }
    catch(e) {
      //alert(e);
      this.setState({ isLoading: false, loginError: e.toString() });
    }
  }

然后我们有登录功能,通过authenticateUser工作流程:

login(username, password) {
  const userPool = new CognitoUserPool({
    UserPoolId: config.cognito.USER_POOL_ID,
    ClientId: config.cognito.APP_CLIENT_ID
  });
  const authenticationData = {
    Username: username,
    Password: password
  };

  const user = new CognitoUser({ Username: username, Pool: userPool });
  const authenticationDetails = new AuthenticationDetails(authenticationData);

  return new Promise((resolve, reject) => (
    user.authenticateUser(authenticationDetails, {
      onSuccess: (result) => { 
        // User authentication was successful
        resolve();
      },
      onFailure: (err) => { 
        var error = err.toString();

        // If password expired
        if (error.includes('Password reset required for the user')) {
          var verificationCode = prompt('Password reset required. Please enter the verification code sent to your trusted device.' ,'');
          var newPassword1 = '';
          var newPassword2 = '';
          while (newPassword1 !== newPassword2 || newPassword1.length < 8) {
            newPassword1 = prompt('Please enter a new password.','');
            newPassword2 = prompt('Please confirm your new password','');
          }

          user.confirmPassword(verificationCode, newPassword1, {
            onSuccess: (result) => {
              //Not sure if this handleSubmit does anything
              //this.handleSubmit;
              this.setState({ loginError: 'Password updated successfully! Please login with new password.', loginAlert: "success", updatePasswordUpdateAttribute: true });
              return;
            },
            onFailure: (err) => {
              this.setState({ loginError: err.toString() });
              reject(err)
            }
          });
        }
        // User authentication was not successful
        console.error(err);
        reject(err) 
      },
      mfaRequired: (codeDeliveryDetails) => {
        // MFA is required to complete user authentication. 
        // Get the code from user and call 
        var verificationCode = prompt('Please enter the multi-factor code sent to your trusted device.' ,'');
        user.sendMFACode(verificationCode, this);
      },
      newPasswordRequired: (userAttributes, requiredAttributes) => {
        // User was signed up by an admin and must provide new 
        // password and required attributes, if any, to complete 
        // authentication.

        // Get these details and call 
        // newPassword: password that user has given
        // attributesData: object with key as attribute name and value that the user has given.
          user.completeNewPasswordChallenge(newPassword1, null, {
            onSuccess: (result) => {
              this.updatePasswordAttribute(user);
              resolve()
            },
            onFailure: (err) => {
              this.setState({ loginError: err.toString() });
              reject(err)
            }
          })          
      }
    })
  ));
}

0 个答案:

没有答案