Get Firebase User.ProviderID on auth/wrong-password when using signInWithEmailAndPassword - firebase

I have an Application that uses Firebase for Authentification.
I allow users to sign in with either Google/Facebook/Twitter or using an Email and Password.
Additionally I have activated within Firebase that Users can only create one account per email.
I want to cover the Following case:
A users signs up with facebook and gets a user account created with their facebook email (e.G. facebookuser#gmail.com).
A few days later the user comes back to the app, but forgot that he signed up using facebook and tries loging in with their email adress facebookuser#gmail.com and their usual password instead.
The firebase.auth().signInWithEmailAndPassword(email, password) method throws an auth/wrong-password error, as no password was given using the facebook login method but the email does exist.
Instead of showing a useless "Wrong password or the account corresponding to the email does not have a password set." error I would like to check instead which provider was used for signing up and reminding the user to sign in with the provider instead.
Unfortunately there doesn't seem to exist a method to get the User.ProviderID for a given email or to understand if the auth/wrong-password error was given because the user typed in a wrong password or if there was no password given in first place as the user signed up with an OAuthProvider instead.

Okay, I have missed the fetchProvidersForEmail method.
Just for Reference: (not the final code I will be using)
Uses signInWithEmailAndPassword to check if a User exists
If it doesn't it creates it using createUserWithEmailAndPassword
If a user exits, it tries to login and catches errors
If the error is auth/wrong-password it checks with fetchProvidersForEmail if the user has used a Provider to sign up
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
// User not found? Create user.
if ( errorCode === 'auth/user-not-found' ) {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if ( errorCode == 'email-already-in-use' ) {
alert('You already have an account with that email.');
} else if ( errorCode == 'auth/invalid-email' ) {
alert('Please provide a valid email');
} else if ( errorCode == 'auth/weak-password' ) {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
// Wrong Password Error
} else if ( errorCode === 'auth/wrong-password' ) {
// Check if User has signed up with a OAuthProvider
firebase.auth().fetchProvidersForEmail(email).then(function( result ){
// … show OAuthProvider Login Button
});
alert('Wrong password. Please try again');
} else {
alert( errorMessage );
}
console.log( error );
});

Related

Is there a way to generate a firebase email verification link before a user is actually signed up?

I am currently implementing a MFA system with Firebase Authentication & Google Authenticator.
Since my users are not allowed to authenticate with a non-verified email address, I'd like to prevent them from signing-in if their Firebase Authentication email_verified is set to false. To do that, I am using Google Cloud Identity Provider blocking functions, this works perfectly.
However, when it comes to the registration beforeCreate blocking function hook, I can't find a way to generate an email verification link for the user currently being created, the documentation says:
Requiring email verification on registration The following example
shows how to require a user to verify their email after registering:
export.beforeCreate = authClient.functions().beforeCreateHandler((user, context) => {
const locale = context.locale;
if (user.email && !user.emailVerified) {
// Send custom email verification on sign-up.
return admin.auth()
.generateEmailVerificationLink(user.email)
.then((link) => {
return sendCustomVerificationEmail(
user.email, link, locale
);
});
}
});
export.beforeSignIn = authClient.functions().beforeSignInHandler((user, context) => {
if (user.email && !user.emailVerified) {
throw new gcipCloudFunctions.https.HttpsError(
'invalid-argument', `"${user.email}" needs to be verified before access is granted.`);
}
});
However, as far as I understand, generateEmailVerificationLink() can only be called to generate email verification link of an existing Firebase Authentication user. At this stage (while running beforeCreate blocking function), the user is not created yet.
Now I am wondering, I am missing something or is the Google documentation wrong?
No.
User data is created upon registration in the database.
Then, you may send an Email-Verification with a link automatically.
This Email-Verification just updates the field emaiVerified of said user data.
If you want to prevent users with unverified Emails from logging in, you need to adjust your Login page and check whether emaiVerified is true.
Important: Google will sign in a user right upon registration whether the email is verified or not, as this is the expected behavior from the perspective of a user. Email verification is ensured on the second, manual login.
(Also, please do not screenshot code.)
You can let a user sign in via email link at first, and call firebase.User.updatePassword() to set its password.
I am using Angular-Firebase, this is the logic code.
if (this.fireAuth.isSignInWithEmailLink(this.router.url)) {
const email = this.storage.get(SIGN_IN_EMAIL_KEY) as string;
this.storage.delete(SIGN_IN_EMAIL_KEY);
this.emailVerified = true;
this.accountCtrl.setValue(email);
from(this.fireAuth.signInWithEmailLink(email, this.router.url)).pipe(
catchError((error: FirebaseError) => {
const notification = this.notification;
notification.openError(notification.stripMessage(error.message));
this.emailVerified = false;
return of(null);
}),
filter((result) => !!result)
).subscribe((credential) => {
this.user = credential.user;
});
}
const notification = this.notification;
const info = form.value;
this.requesting = true;
form.control.disable();
(this.emailVerified ? from(this.user.updatePassword(info.password)) : from(this.fireAuth.signInWithEmailLink(info.account))).pipe(
catchError((error: FirebaseError) => {
switch (error.code) {
case AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY.POPUP_CLOSED_BY_USER:
break;
default:
console.log(error.code);
notification.openError(notification.stripMessage(error.message));
}
this.requesting = false;
form.control.enable();
return of(null);
}),
filter((result) => !!result)
).subscribe((result: firebase.auth.UserCredential) => {
if (this.emailVerified) {
if (result.user) {
notification.openError(`注册成功。`);
this.router.navigateByUrl(this.authService.redirectUrl || '');
} else {
notification.openError(`注册失败。`);
this.requesting = false;
form.control.enable();
}
} else {
this.storage.set(SIGN_IN_EMAIL_KEY, info.account);
}
});
Mate, if database won't create a new user using his email and password, and you send him email verification which will create his account, how the heck database will know his password? If it didn't create his account in the first step? Stop overthinking and just secure database using rules and routes in application if you don't want user to read some data while he didn't confirm email address.
It is that simple:
match /secretCollection/{docId} {
allow read, write: if isEmailVerified()
}
function isEmailVerified() {
return request.auth.token.email_verified
}
I think the blocking function documentation is wrong.
beforeCreate: "Triggers before a new user is saved to the Firebase Authentication database, and before a token is returned to your client app."
generateEmailVerificationLink: "To generate an email verification link, provide the existing user’s unverified email... The operation will resolve with the email action link. The email used must belong to an existing user."
Has anyone come up with a work around while still using blocking functions?
Using firebase rules to check for verification isn't helpful if the goal is to perform some action in the blocking function, such as setting custom claims.

Apple sign in causes FIRAuthErrorUserInfoNameKey=ERROR_EMAIL_ALREADY_IN_USE (Code = 17007)

Using SwiftUI, Xcode12.5.1, Swift5.4.2, iOS14.7.1,
My Firebase-Email/Password Login-page shall be extended with other Login possibilities such as Apple-Login (eventually Google-login, Facebook-login etc).
My steps:
log in with Email/Password to Firebase
log out
log in with "Sign in with Apple"
--> Then I get the following error:
Error Domain=FIRAuthErrorDomain Code=17007
"The email address is already in use by another account."
UserInfo={NSLocalizedDescription=The email address is already in use by another account.,
FIRAuthErrorUserInfoNameKey=ERROR_EMAIL_ALREADY_IN_USE}
What I intended to do is to link the existing Email/Password-Firebase-Account to the Sign in with Apple-Account (as described here and here).
But for doing that I would need the error FIRAuthErrorUserInfoUpdatedCredentialKey that allows to retrieve the old user eventually.
In my case, I get ERROR_EMAIL_ALREADY_IN_USE which does not lead to any old user to be linked.
What do I have to do ?
Here is my code:
let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)
Auth.auth().signIn(with: credential) { (authResult, error) in
if (error != nil) {
print(error?.localizedDescription as Any)
return
}
print("signed in with Apple...")
do {
// if user did log in with Email/Password previously
if let email = try THKeychain.getEmail(),
let password = try THKeychain.getPassword() {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
if let user = authResult?.user {
// here I am trying to link the existing Firebase-Email/Password account to the just signed-in with Apple account
user.link(with: credential) { (result, linkError) in
print(linkError) // this is where I get FIRAuthErrorUserInfoNameKey=ERROR_EMAIL_ALREADY_IN_USE
// unfortunately, the two accounts are not linked as expected due to this error !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// What is missing ??????????????????
loginStatus = true
}
}
} else {
loginStatus = true
}
} catch {
print(error.localizedDescription)
}
}
On the Firebase-documentation it sais:
Sign in with Apple will not allow you to reuse an auth credential to link to an existing account. If you want to link a Sign in with Apple credential to another account, you must first attempt to link the accounts using the old Sign in with Apple credential and then examine the error returned to find a new credential. The new credential will be located in the error's userInfo dictionary and can be accessed via the FIRAuthErrorUserInfoUpdatedCredentialKey key.
What does the part "...If you want to link a Sign in with Apple credential to another account, you must first attempt to link the accounts using the old Sign in with Apple credential..." exactly mean ? WHAT IS THE old Sign in with Apple credential ????????
And how would I do that ?
In fact, at the linking-call, I actually expected some sort of linkError.userInfo with an updated user to sign in with. But the linkError in my example only gives me the ERROR_EMAIL_ALREADY_IN_USE error without further userInfo.
As Peter Friese mentions in his Blog, I should somehow be able to retrieve a AuthErrorUserInfoUpdatedCredentialKey from the error.userInfo. But in my case, the linkError does not have any kind of such information - unfortunately!
Here is an excerpt of Peter's example: (again not applicable in my case for some unknown reason?????)
currentUser.link(with: credential) { (result, error) in // (1)
if let error = error, (error as NSError).code == AuthErrorCode.credentialAlreadyInUse.rawValue { // (2)
print("The user you're signing in with has already been linked, signing in to the new user and migrating the anonymous users [\(currentUser.uid)] tasks.")
if let updatedCredential = (error as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as? OAuthCredential {
print("Signing in using the updated credentials")
Auth.auth().signIn(with: updatedCredential) { (result, error) in
if let user = result?.user {
// TODO: handle data migration
self.doSignIn(appleIDCredential: appleIDCredential, user: user) // (3)
}
}
}
}
}
Reversing the order of linking made me advance a tiny bit.
If I press the Sign in with Apple button, my code now logs in with Firebase-Email/Password first (i.e. the necessary credentials are taken from the Keychain). And on a second step, links with the Apple-credentials. And by doing so, the linking finally gives me the desired AuthErrorUserInfoUpdatedCredentialKey in the link-callback.
There I retrieve the updatedCredential to log in with Apple.
See code below.
HOWEVER, I STILL DON'T KNOW WHY AFTER LOGIN THIS WAY, MY DATA IS STILL MISSING ???????
HOW DOES THIS DATA-MIGRATION STEP WORK ???
Shouldn't the user.link(with: appleCredentials) { ... } do the job ?
What do I need to do in order to get the very same Firebase-Data, no matter the login method ???
let appleCredentials = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)
do {
// if user did log in with Email/Password anytime before
if let email = try THKeychain.getEmail(),
let password = try THKeychain.getPassword() {
let firebaseEmailCredentials = EmailAuthProvider.credential(withEmail: email, password: password)
Auth.auth().signIn(with: firebaseEmailCredentials) { (authResult, error) in
if let user = authResult?.user {
user.link(with: appleCredentials) { (result, linkError) in
if let linkError = linkError, (linkError as NSError).code == AuthErrorCode.credentialAlreadyInUse.rawValue {
print("The user you're signing in with has been linked.")
print("Signing in to Apple and migrating the email/pw-firebase-users [\(user.uid)]` data.")
if let updatedCredential = (linkError as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as? OAuthCredential {
print("Signing in using the updated credentials")
Auth.auth().signIn(with: updatedCredential) { (result, error) in
if let _ = result?.user {
print("signed in with Apple...")
// TODO: handle data migration
print("Data-migration takes place now...")
loginStatus = true
}
}
}
}
else if let error = error {
print("Error trying to link user: \(error.localizedDescription)")
}
else {
if let _ = result?.user {
loginStatus = true
}
}
}
}
}
} else {
// case where user never logged in with firebase-Email/Password before
Auth.auth().signIn(with: appleCredentials) { (result, error) in
if let _ = result?.user {
print("signed in with Apple...")
loginStatus = true
}
}
}
} catch {
print(error.localizedDescription)
}

Linking social provider with anonymous user on two devices

When a user start using our app we log him in using Firebase anonymous login.
We later allow them to login with social providers like Apple. We use the "auth().currentUser?.linkWithCredential" to link the social credentials with the anonymous user id.
We encountered a situation we are not sure how to solve:
User install the app on the device and use Sign in with Apple to sign in. We link the anonymous account to the Apple login and everything works just fine.
But now the user buys a new device. He installs the app and start it. He gets a new anonymous uid. He then try to sign in with Apple. Now if we try to call linkWithCredential we get an error:
"auth/credential-already-in-use] This credential is already associated with a different user account"
This is of course true, as the Apple credentials were associated with the anonymous user on the old device.
So how do we allow a user to sign in again from a new device?
We thought to catch the error, and then call signInWithCredential instead of linkWithCredential. But then we get an error:
Duplicate credential received. Please try again with a new credential.
It seems you can't use the Apple credentials for more than one call.
So again - we are stuck with no way to allow a user to login in two devices.
let appleAuthRequestResponse = null;
try {
appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: AppleAuthRequestOperation.LOGIN,
requestedScopes: [
AppleAuthRequestScope.EMAIL,
AppleAuthRequestScope.FULL_NAME,
],
});
} catch (err) {
// TODO: decide what to do
return;
}
const {
identityToken,
nonce
} = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(
identityToken,
nonce
);
let userCredentials = null;
try {
userCredentials = await auth().currentUser ? .linkWithCredential(
appleCredential
);
// This will work on the first device but fail on the second one
console.log(userCredentials);
} catch (err) {
// This will fail as well with error: Duplicate credential received
await auth().signInWithCredential(appleCredential)
}

Firebase: Check through cloud functions if user email is verified

Is there a way to check if email is verified through cloud functions
i.e. if I have a uid for the user, can I check if the email is verified for that particular user. In my use case, I need to make sure that email is verified before transaction is executed. I want to check it server side
Sample cloud function:
exports.executeTransaction = functions.https.onCall((data,context)=>{
const userid = context.auth.uid
//Check if email is verified
//I want to use context variable to somehow extract whether email is verified. Is there a way to do it ?
//Execute Transaction if email is verified
})
Never Mind, I managed to figure it out.
See following for anyone with similar issue:
exports.executeTransaction = functions.https.onCall((data,context)=>{
const userid = context.auth.uid
//Check if email is verified
return admin.auth().getUser(context.auth.uid).then(user => {
//Check if email verified
if(user.emailVerified)
{
return "Verified"
}
else{
console.log("User Email not verified")
return "Not Verified"
}
}).catch(function(err){
console.log(err)
throw new functions.https.HttpsError('Error Validating', err.message, err)
})
})
According to the docs, context includes decodedIdToken, which already contains an email_verified field.
Thus all you need to do is this:
exports.executeTransaction = functions.https.onCall((data, context) => {
const { token } = context.auth;
if (!token.firebase.email_verified)
throw new functions.https.HttpsError(
"failed-precondition",
"The function must be called while authenticated."
);
// ...do stuff
})
https://firebase.google.com/docs/reference/functions/functions.https#.CallableContext
https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken#email_verified

Firebase. Change `username`(email) of registered user

My iOS application uses Firebase login by username and password. But I would like to give a possibility to change the username in settings.
The question is, does Firebase support changing a username?
Update
username means email
If you want to change the displayName you can use this code:
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = "DoesData"
changeRequest?.commitChanges { (error) in
// ...
}
If you want to change the email address you can use:
currentUser?.updateEmail(email) { error in
if let error = error {
print(error)
}
else {
// Email updated
}
}
I know you have to reauthenticate if you update a users password, but I'm not sure if you need to do that for email changes as well.
This code can help with authentication:
let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
let currentUser = FIRAuth.auth()?.currentUser
currentUser?.reauthenticateWithCredential(credential) { error in
if let error = error {
// An error happened.
} else {
// User re-authenticated.
}
}
You may also want to look at documentation, this question, and this question
I guess you're talking about the email and password auth method.
You can change the email (which is the username) by updating it directly from code. Hope this helps!

Resources