如何检查电子邮件已存在于 AWS Cognito 中?

Sai*_*ath 8 javascript amazon-web-services amazon-cognito

我正在使用 AWS Cognito 进行登录/注册。我们有两步之遥。

1)它会要求提供电子邮件。2)如果电子邮件已经存在,那么它会询问密码,否则它会说创建密码。此步骤上的按钮根据上述条件显示为登录或注册。

在用户输入电子邮件后,我需要一种使用 AWS javascript SDK 签入 cognito 的方法来检查已注册的电子邮件。

谢谢,

Tho*_*988 13

  1. 如果您想使用 aws amplify 检查用户是否存在于前端,我在这里找到了答案https://github.com/aws-amplify/amplify-js/issues/1067

     userExist(email: string) {
        return Auth.signIn(email.toLowerCase(), '123').then(res => {
            return false;
        }).catch(error => {
         const code = error.code;
         console.log(error);
         switch (code) {
             case 'UserNotFoundException':
                 return !this.redirectToRegister(email);
             case 'NotAuthorizedException':
                 return true;
             case 'PasswordResetRequiredException':
               return !this.forgotPassword(email);
             case 'UserNotConfirmedException':
                 return !this.redirectToCompleteRegister(email);
             default:
                 return false;
         }
       });
     }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果你想用nodeJS在服务器端检查用户是否空闲并且尚不存在

     checkIfUserDoesntExist(email) {
     return new Promise(async (resolve, reject) => {
         const payload = {
             ClientId: configCognito.APP_CLIENT_ID,
             AuthFlow: "ADMIN_NO_SRP_AUTH",
             UserPoolId: configCognito.USER_POOL_ID,
             AuthParameters: {
                 USERNAME: email,
                 PASSWORD: "123",
             }
         }
         try {
             await (new AWS.CognitoIdentityServiceProvider()).adminInitiateAuth(payload).promise();
             reject(); // very unlikely 
         } catch (e) {
             console.log("checkIfUserDoesntExist error", e);
             switch (e.code) {
                 case 'UserNotFoundException':
                     resolve();
                 case 'NotAuthorizedException':
                 case 'PasswordResetRequiredException':
                 case 'UserNotConfirmedException':
                 default:
                     reject();
             }
         }
       });
     }
    
    Run Code Online (Sandbox Code Playgroud)


小智 4

Amazon Amplify 通过从 Angular/React 中的 aws-amplify 导入身份验证,使登录和注册过程变得非常简单。在我的登录页面上,我要求每个用户注册,无论他们的电子邮件是否已经存储在用户池中。如果用户已注册,Cognito 会引发“UserExistsException”异常,该异常可以在 Auth.signUp Promise 中捕获,如下所示:

public cognitoSignUp(username, password, email){ Auth.signUp({ username, password, attributes: { email,
}, validationData: [] }) .then(data => { console.log(data) }) .catch(error => { //The user has already registered so go to the SignIn method if(error['code'] === "UsernameExistsException"){ this.cognitoSignIn(username, password); } else{ console.log(error) } }); }

希望我的回答有用。