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,
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;
}
});
}
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();
}
}
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With