How to check Email Already exists in AWS Cognito?

11,313

Solution 1

  1. If you want to check if user exists on Front-end with aws amplify, i found the answer here 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;
         }
       });
     }
    
  2. If you want to check on server side with nodeJS if the user is free and doesn't already exist

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

Solution 2

Amazon Amplify makes the signIn and signUp process very straightforward with the Auth importation from aws-amplify in Angular/React. On my login page I ask every user to sign up whether or not their email is alrealdy stored in the user pool. If a user is registered, Cognito raises a "UserExistsException" exception which can be catch in the Auth.signUp promise like so :

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

Hope that my answer was useful.

Share:
11,313
Sainath
Author by

Sainath

Updated on July 19, 2022

Comments

  • Sainath
    Sainath almost 2 years

    I am using AWS Cognito for signin/signup. We have two step from.

    1) It will ask for email. 2) If email already exists then it will ask Password or otherwise it will say create password. Button on this step displayed based on the above condition either Login or Register.

    Here after user enters email, I need a way to check in cognito with AWS javascript SDK to check email already registered or not.

    Thanks,

  • Abhinab Rajopadhyaya
    Abhinab Rajopadhyaya over 3 years
    How do we get congitoService and what is this referring to here
  • Azher Aleem
    Azher Aleem about 3 years
    @ThomasP1988 Is the Cognito service object created from AWS javascript sdk?
  • Azher Aleem
    Azher Aleem about 3 years
    @ThomasP1988, Taking about point 1, if the user already exists in cognito pool wouldn't Auth.SignIn log the user in rather than just checking for existence?
  • ThomasP1988
    ThomasP1988 about 3 years
    only if the user password is "123" which is very unlikely, the goal is to pass a wrong password.
  • Azher Aleem
    Azher Aleem about 3 years
    @ThomasP1988 To give you a background of what my scenario is: I have a Cognito pool set up with Amplify together with social logins from Facebook and Google. I want if the user signs up from an email address say. '[email protected]' from either a social provider or from the normal sign-up page provided then he cannot sign up again from a social or normal signup page if the user with '[email protected]' exists in the pool.
  • Azher Aleem
    Azher Aleem about 3 years
    I have implemented this using a pre sign up lambda trigger however if the user exists and I try to sign up with social login let's say Facebook it redirects me to the specified redirect URL and the exception remains for a while in the URL which I want it to be shown in a toast message that a user with the same email already exists. So, I am trying to cater this in the front end but I cannot find any Auth class functions to check for existance of email id in the pool. Any leads would help
  • ThomasP1988
    ThomasP1988 about 3 years
    Ok, so in that case, this solution seems good, try to log this mail address with a dummy password, and you will be able to detect if this mail already exists in your pool, if it doesnt exist then you can carry on with social login.
  • Azher Aleem
    Azher Aleem about 3 years
    @ThomasP1988 sure, I’ll try it out. But i guess i should log a feature request on amplify to provide such a method
  • Kukula Mula
    Kukula Mula about 3 years
    @ThomasP1988 I'm getting AccessDeniedException assumed-role/myClientApp/id is not authorized to perform: cognito-idp:AdminInitiateAuth on resource: aws:cognito-idp:us-east-1:userpool/us-east-1 any ideas?
  • ThomasP1988
    ThomasP1988 about 3 years
    are you using serverless framework or amplify? are you trying to check or front end or back end?