In my application using Ionic 4 with Firebase/AngularFire2, I authenticate users with the signinwithemeailandpassword()
method. I need to verify if it's the first time a user is logging in after registering. Firebase provides the option to check this using isNewUser
.
When a new account is created with createUserWithEmailAndPassword()
, the value of isNewUser is set to true
, which is expected. However, when logging in with signinwithemeailandpassword()
, the value always returns false, regardless of whether it's the first login or not.
Here is the code for the login method:
async login(form: NgForm) {
// Validate the login form
if (form.invalid)
return this.statusMessage.message('Validation error!');
console.log(this.user);
try {
const results = await this._afAuth.auth.signInWithEmailAndPassword(this.user.email, this.user.password).then(
user => console.log(user.additionalUserInfo.isNewUser)
);
// console.log(results);
} catch (error) {
switch (error.code) {
case "auth/user-not-found":
this.statusMessage.message("Your email address is wrong! Please try again");
break;
case "auth/invalid-email":
this.statusMessage.message("You have entered an invalid email address");
break;
case "auth/wrong-password":
this.statusMessage.message('The password you entered is wrong');
break;
default:
console.dir(error);
this.statusMessage.message('Something went wrong! Please try again later');
break;
}
}
And here is the signup code:
async register(form: NgForm) {
// Check form validation
if (form.invalid) return this.statusMessage.message('Validation error!');
console.log(this.user);
try {
await this.afAuth.auth.createUserWithEmailAndPassword(this.user.email, this.user.password).then(
user => console.log(user)
);
} catch (error) {
this.statusMessage.message('Something went wrong! Please try again later.');
}
}
}