Check if user phone_number already exist in aws cognito userpool

979 views Asked by At

I am using serverless lambda functions on aws for user authentication in cognito user-pool. I am asking the user only for his phone_number and sending him otp for verification. The problem arises, when the user signs out and sign-in again. I am unable to decide on when to call signUp or sign-in for the user. I am guessing that, I need a lambda call to be triggered before the pre-signup, which verifies that the user phone number already exists in the user-pool, and I need to call the Amplify.Auth.signIn api from the client. If not then call Amplify.Auth.signUpapi from the client. But I am unable to find any document for that. I am using flutter as my front-end. Please help.

My pre-signup lambda functions looks something like this:

exports.handler = async (event) => {
    console.log('Received EVENT', JSON.stringify(event, null, 2));
    event.response.autoConfirmUser = true;
    event.response.autoVerifyPhone = true;
    return event;
};
1

There are 1 answers

3
qasimalbaqali On

You can use the CognitoIdentityServiceProvider.listUsers for this.

const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider();

const result = await this.cognitoIdentityServiceProvider.listUsers({
 UserPoolId: process.env.USER_POOL_ID,
 Filter: `phone_number = \"${phoneNumber}\"`
}).promise();

return result.Users.length > 0 ? result.Users[0].Username : undefined;