amplify-js: How to verify if a user with a given email already exists in User Pool?

Do you want to request a feature or report a bug?

Question

What is the expected behavior?

Check is user exists

example

Is there such a method?

Auth.verifyIfUserExists({
    email: 'foo@bar.com'
})
.then(res => {
    // user with this email already exists
})

Because now I can find out if a user exists ONLY during signUp action. But I want to check it before I do signUp. Because if a user doesn’t exist it will be created right off the bat. And it is not what expected

Auth.signUp({
        username,
        password,
        attributes: {
        },
    })
    .then(data => console.log(data))
    .catch(err =>{
        // User exists !!
    });

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 31
  • Comments: 45 (2 by maintainers)

Most upvoted comments

@wzup

There is not function that does this and only this; however, I think if you use the confirmSignUp function and are using email as an alias you will get back an AliasExistsException error.

In any case I am marking this as a feature request, as it seems useful.

Thanks for your feedback.

I looked at the amplify source code.

Auth.confirmSignup() calls cognitoUser.confirmRegistration(code, forceAliasCreation) which then calls this API: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html

The right way to do this (without signIn & signOut) according to the project contributors seems to be this:

const code = '000000'
Auth.confirmSignUp(username, code, {
    // If set to False, the API will throw an AliasExistsException error if the phone number/email used already exists as an alias with a different user
    forceAliasCreation: false
}).then(data => console.log(data))
  .catch( err => {
        switch ( err.code ) {
            case 'UserNotFoundException':
                return true;
            case 'NotAuthorizedException':
                return false;
            case 'AliasExistsException':
                // Email alias already exists
                return false;
            case 'CodeMismatchException':
                return false;
            case 'ExpiredCodeException':
                return false;
            default:
                return false;
        }
    } )

@wzup The sign-in workaround might work just because User Pools require passwords that are 6-characters are longer so in practice, there will never be a user account whose password is ‘123’.

@haverchuck However, even if this workaround works, it’s really bad that the API doesn’t support checking the existence of a user name directly. I’ve been working with Cognito for two years and this feature already exists as a request, but hasn’t been implemented yet, along with the ability for an administrator to reset an account’s password. The combination of these two problems makes it quite difficult to build enterprise applications.

I did:

 userExist(userName: string) {
      return Auth.signIn(userName, '123');
    }
and

userExist(email: string) {
    return this.cognitoService.userExist(email.toLowerCase()).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;
        }
    });
    }

I always get error code ExpiredCodeException with message Invalid code provided, please request a code again.

@PavolHlavaty I was experiencing the same issue as you until reading these docs: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-managing-errors.html

Basically the PreventUserExistenceErrors option has to be disabled (ie. enable user existence errors) for your app client, where it was enabled by default in my config.

It can be changed in Cognito console with: User pools > Selecting your user pool > General settings > App clients > Show Details > Security configuration > Legacy > Save app client changes

With my default setup of amplify I have two app clients (native and web), and ended up changing it for both of them, although don’t know if it that was necessary.

@michelmob @haverchuck

But what if credentials are correct?

Auth.signIn(userName, '123');

Then a user that wants to sign up will be suddenly signed in instead.

This is definitely bad experience from aws-amplify.

This is an abstraction of cognito using aws amplify.

Sent from my iPhone

On 21 Jun 2018, at 03:13, wzup notifications@github.com wrote:

@michelmob , thank you.

One question though. What is this in your example? Where does .cognito live?

return this.cognitoService.userExist( email.toLowerCase() ) — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

@haverchuck

Here is why requested method I ask for is important.

With current authflow we have to signin and then signout a user just to check if an email (username) already exists:

// 1. In order to check if an email already exists in Cognito we have to call .signIn.
// Because there is no special method for that, like Auth.doesUsernameExists(username)
Auth.signIn( email, password )
    .then( user => {
        // 2. I a user found, they get signin
        // You have to log out a user if found
        // Security vulnerability
        return Auth.signOut();
    } )
    .then( res => {
        // 3. Here we show a user that email is taken
        // After logging them in and logging them out. LOL
        this.setState((state, props) => {
            return {
                emailError: 'This email is already taken'
            };
        });
        return;     
    } )
    .catch( err => {
        switch ( err.code ) {
            case 'UserNotFoundException':
                // Only here, in .catch error block we actually send a user to sign up
                return this.signUp();
            case 'NotAuthorizedException':
                return true;
            case 'PasswordResetRequiredException':
                return false;
            case 'UserNotConfirmedException':
                return this.props.navigation.navigate('ConfirmRegistrationScreen', {
                    username: email,
                });
            default:
                return false;
        }
    } )

Any implementations yet? the feature request happened 5 years ago now.

+1 in seeing URL.host is not implemented, what was the fix you found for that?

Is there an update on this issue? Tried all the solutions above and nothing worked. This issue has been open for too long. Will Amazon ever consider implementing this feature?

The only way I’ve found to do this consistently in a way that’s not too much of a hack is the following:

  • allow email addresses to be used as an alias for username and use some custom method to create the actual username, e.g. UUID
  • Use the listUser API call with the candidate new user account’s email address
  • If no results are returned then the email address does not exist for any user

The consequence of this is email addresses must be unique per account.

The reason this will work and not getUser is that getUser only returns accounts with verified email address. To be complete you need to check to see if the user has tried to register for an account in the past but never confirmed their email address.

Hope this helps a bit.

Clinton

Came across this issue and @heri16’s solution worked perfect. If you’re looking for something to just paste in and go, here’s a snippet:

const usernameAvailable = async (username) => {
  // adapted from @herri16's solution: https://github.com/aws-amplify/amplify-js/issues/1067#issuecomment-436492775
  try {
    const res = await Auth.confirmSignUp(username, '000000', {
      // If set to False, the API will throw an AliasExistsException error if the phone number/email used already exists as an alias with a different user
      forceAliasCreation: false
    });
    // this should always throw an error of some kind, but if for some reason this succeeds then the user probably exists.
    return false;
  } catch (err) {
    switch ( err.code ) {
      case 'UserNotFoundException':
          return true;
      case 'NotAuthorizedException':
          return false;
      case 'AliasExistsException':
          // Email alias already exists
          return false;
      case 'CodeMismatchException':
          return false;
      case 'ExpiredCodeException':
          return false;
      default:
          return false;
    }
  }
}

To use:

const available = await usernameAvailable(emailAddress);
console.log(`user ${available ? 'available' : 'not available'}`);

When I try to use solution proposed by @heri16. I always get error code ExpiredCodeException with message Invalid code provided, please request a code again.

Is there an update on this issue? Tried all the solutions above and nothing worked. This issue has been open for too long. Will Amazon ever consider implementing this feature?

@michelmob , thank you.

One question though. What is this in your example? Where does .cognito live?

return this.cognitoService.userExist( email.toLowerCase() )

@akeditzz if you are using mobile number remember to use e164 format only. Country specific phone strings will give you issues

@akeditzz it’ll work, i use mobile number personally but have tested both. but same rules apply as for email. if signed up it needs to be verified or it won’t work properly. Personally in my case if something goes wrong and user wasn’t able to confirm, i just make him signup again with another username (random uuid in my case). So there will be two accounts created in cognito pool but only one will be confirmed and thus used for future login.

@wzup

There is not function that does this and only this; however, I think if you use the confirmSignUp function and are using email as an alias you will get back an AliasExistsException error.

In any case I am marking this as a feature request, as it seems useful.

Thanks for your feedback.