Converting Firebase anonymous user to user with email and password - Flutter - firebase

I'm having trouble to convert an anonymous Firebase user to a registered user with email and password.
My code look's like this:
Future linkAnonymousAccount({
required String email,
required String password,
}) async {
try {
await _auth.currentUser!.linkWithCredential(
auth.EmailAuthProvider.credential(email: email, password: password),
);
// await refreshUser();
} on auth.FirebaseAuthException catch (e) {
throw LinkAnonymousAccountException(e.code);
}
}
It seem's like EmailAuthProvider.credential creates a new user (with new uuid and everything) instead of converting the current anonymous user.
So after creating an anonymous user with:
Future signInAnonymously() async {
try {
await _auth.signInAnonymously();
} on auth.FirebaseAuthException catch (e) {
throw SignInException(e.code);
}
}
And then calling the linkAnonymousAccount - method from above I get the following result in my firebase console:
But so I lose all user data like displayName and photoUrl and also all the data in my database (due to the different uuid's).
I'm not able to find a solution for this or an explanation why this is happening.
I found a video where this is not the case and the anonymous user is actually converted. But I use the same code as the guy in the video and get a different result.
Am I missing something? Has someone an explanation for this?

Related

When does creationTime or lastSignInTime of firebase.auth.UserMetadata returned as null/undefined?

I bumped into this issue while trying to create user document in Firestore after a new user is signed up using Firebase Authentication.
In user document, I want to include creationTime and lastSignInTime fields but found out that those fields are optional. That means I would have to make those fields in my user document optional as well but I am not quite convinced why they should be optional in the first place. I just cannot think of a case where those fields in metadata of User instance should be set as undefined when it is returned after successful sign up/in using Firebase Auth.
If there's no specific case where they're returned as undefined, I'm planning to make those fields in my user document as required fields, and throw error just in case they are returned as undefined.
For example using react-native-firebase:
try {
const { user } = await auth().signInAnonymously();
const {
metadata: { creationTime, lastSignInTime },
uid,
} = user;
if (creationTime == null) {
throw new TypeError('creationTime is returned as undefined');
}
if (lastSignInTime == null) {
throw new TypeError('lastSignInTime is returned as undefined');
}
await firestore().collection('user').doc(uid).set({
creationTime,
lastSignInTime,
// other fields
});
} catch (error) {
// handle error
}
But if not, then no choice but to have them as optional as well.
So wrapping up the question, is there any case where creationTime or lastSignInTime is set to undefined/null? Is it safe to just treat them as required fields?
(A similar issue is posted here but it's closed with no answer.)
I'm not sure about creationTime but lastSignInTime can be undefined/null if the sign-up has occurred but the user has not signed in yet. For example the user might have to complete email verification or something along those lines.

Firebase Login and Login with Apple not linking to same user account

Using SwiftUI, Xcode12.5.1, Swift5.4.2, iOS14.7.1,
My Firebase-Login page shall be extended with other Login possibilities such as Apple-Login (eventually Google-login, Facebook-login etc).
I have an implementation of Firebase-Login that works well.
I extended the LoginView with the Sign in with Apple Button.
And this new Apple Login in its basic implementation also works.
Now the problem:
If I log in with Apple, I need to access the corresponding Firebase-user in order to query the correct user-data. Right now, login in with Apple works but the retrieved data is not the user-data of the corresponding Firebase-user.
What I want to achieve:
From a logout-state, I want to
a) Being able to log in with Firebase Email/Password and sometimes later want to log-out and log in again with Apple.
--> and for both cases, I would like to get the same user-data
b) Being able to log in with Apple and sometimes later want to log-out and log in again with Firebase Email/Password
--> and for both cases, I would like to get the same user-data
--- THE IDEA ----------
I learned from the Firebase documentation that there is a way to link two login-accounts that we are able to know that these two accounts are corresponding.
--- THE IMPLEMENTATION -----------
Below is my current implementation for the Apple login:
I learned that you can get userInformation of the corresponding other account in the error of the link-callback. But in my case, I get the wrong linkError:
My linkError:
The email address is already in use by another account.
Instead of:
AuthErrorCode.credentialAlreadyInUse
For me this doesn't make sense. Especially since I know that I already did log in before with Firebase-Email/Password. Then I logged out and now I tried to log in with Apple.
Shouldn't the link method recognise that I am allowed to have been logged in via Firebase-Email/Password before and shouldn't it be ok to have that email being used before ?? I don't understand this linkError.
Questions:
In the link-callback, why do I get the linkError The email address is already in use by another account. instead of AuthErrorCode.credentialAlreadyInUse ??
What do I need to change in order to make a) work ??
How does the implementation look for the b) workflow (i.e. if user logs in to Apple, then logs-out and logs in again with Firebase-Email/Password ??). How do I link the two accounts then ??
Here my code:
switch state {
case .signIn:
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
print("Error authenticating: \(error.localizedDescription)")
return
}
do {
if let email = try THKeychain.getEmail(),
let password = try THKeychain.getPassword() {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
if let user = authResult?.user {
user.link(with: credential) { (result, linkError) in
if let linkError = linkError, (linkError as NSError).code == AuthErrorCode.credentialAlreadyInUse.rawValue {
print("The user you're signing in with has already been linked, signing in to the new user and migrating the anonymous users [\(user.uid)] tasks.")
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 user = result?.user {
// eventually do a data-migration
user.getIDToken { (token, error) in
if let _ = token {
// do data migration here with the token....
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
}
}
else if let linkError = linkError {
// I END UP HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WHY WHY WHY WHY WHY WHY WHY WHY ????????????????????????
print("Error trying to link user: \(linkError.localizedDescription)")
}
else {
if let user = result?.user {
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
}
} catch {
print(error.localizedDescription)
}
if let user = authResult?.user {
if let onSignedInHandler = self.onSignedInHandler {
onSignedInHandler(user)
}
}
}
case .link:
// t.b.d.
case .reauth:
// t.b.d.
}

Check if an email already exists in Firebase Auth in Flutter App

I'm currently developing a flutter app that requires users to register before using it. I use Firebase Authentication and would like to check whether an email is already registered in the app.
I know the easy way to do it is to catch the exception when using the createUserWithEmailAndPassword() method (as answered in this question). The problem is that I ask for the email address in a different route from where the user is registered, so waiting until this method is called is not a good option for me.
I think the best option would be to use the method fetchProvidersForEmail(), but I can't seem to make it work.
How do I use that method? Or is there a better option to know if an email is already registered?
The error raised is a PlatformException
so you can do something as follows-
try {
_firbaseAuth.createUserWithEmailAndPassword(
email: 'foo#bar.com',
password: 'password'
);
} catch(signUpError) {
if(signUpError is PlatformException) {
if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
/// `foo#bar.com` has alread been registered.
}
}
}
The following error codes are reported by Firebase Auth -
ERROR_WEAK_PASSWORD - If the password is not strong enough.
ERROR_INVALID_EMAIL - If the email address is malformed.
ERROR_EMAIL_ALREADY_IN_USE - If the email is already in use by a different account.
There is no such fetchProvidersForEmail method anymore in the current version of the firebase auth package. The equivalent one is now fetchSignInMethodsForEmail method which I think would be the best option to handle this case without executing any unnecessary operation.
fetchSignInMethodsForEmail
In docs, it's stated that this method returns an empty list when no user found, meaning that no account holds the specified email address:
Returns a list of sign-in methods that can be used to sign in a given
user (identified by its main email address).
This method is useful when you support multiple authentication
mechanisms if you want to implement an email-first authentication
flow.
An empty List is returned if the user could not be found.
Based on this, we could create our own method like the following one:
// Returns true if email address is in use.
Future<bool> checkIfEmailInUse(String emailAddress) async {
try {
// Fetch sign-in methods for the email address
final list = await FirebaseAuth.instance.fetchSignInMethodsForEmail(emailAddress);
// In case list is not empty
if (list.isNotEmpty) {
// Return true because there is an existing
// user using the email address
return true;
} else {
// Return false because email adress is not in use
return false;
}
} catch (error) {
// Handle error
// ...
return true;
}
}
I think the only possibility from within the app is attempting a login (signInWithEmailAndPassword) with that e-mail and check the result.
If it's invalid password, the account exists.
If it's invalid account, the account do not exist.
Error 17011
There is no user record corresponding to this identifier. The user may have been deleted
Error 17009
The password is invalid or the user does not have a password
As this is a kind of an ugly solution, you can justify this additional call using it to check it the e-mail formatting is correct (according to the firebase rules). If it doesn't comply it will throw a address is badly formatted and you can alert the user soon enough.
You can do these checks using the error codes with current versions of the plug-in.
There are many ways you can do that. As Sakchham mentioned, you could use that method. There is another method you could use which in my opinion is better and safer.
Since the password value will return ERROR_WEAK_PASSWORD, it is a create account method which you are calling which means that it's possible an account will be created if the account doesn't exist, in that case, I recommend personally using the sign in with email method.
I used this code below:
Future<dynamic> signIn(String email) async {
try {
auth = FirebaseAuth.instance;
await auth.signInWithEmailAndPassword(email: email, password: 'password');
await auth.currentUser.reload();
return true;
} on FirebaseAuthException catch (e) {
switch (e.code) {
case "invalid-email":
return 'Your username or password is incorrect. Please try again.';
break;
}
}
}
Leave down a comment if you have any suggestions.
I didn't think fetchProvidersForEmail() method is available in the firebase package. So we can show the appropriate message to the user. you can create more case if you need.
try {
await _auth.signInWithEmailAndPassword(
email: "Hello#worl.com",
password: "123456789"
);
} catch (e) {
print(e.code.toString());
switch (e.code) {
case "email-already-in-use":
showSnackBar(context,"This Email ID already Associated with Another Account.");
break;
}
}

Can't change password and login at same time in Meteor

In my Meteor app, users are invited based on their email, then proceed to set their own password. I want the users to land on the page and then set the password. From there, they will be logged into the account. I am able to set the users password, but can not log them in immediately after.
This is how I have my code:
Client Side
Meteor.call('setStudentPassword', password, id, function (error, result) {
if (!error) {
Meteor.loginWithPassword(id, password, function (error) {
console.log(error);
Router.go('studentCreditCard');
});
}
});
Server Method
setStudentPassword: function(password, id) {
if (Meteor.isServer) {
return Accounts.setPassword(id, password);
}
}
Is this possible to do, or will I need to set a temporary password on account creation?
You can't write Meteor.loginWithPassword(id [...]) according to the docs, but have to write Meteor.loginWithPassword({id: id} [...]) instead.
But more importantly: anyone can call the method setStudentPassword, and change the password for anyone. A huge security risk, I strongly advice you against using this code. Further more, the users password is sent over the wire in plain text, which should be avoided.

How do I remember a logged user using AngularFire and Firebase Simple Login?

This is what I'm using for Authentication:
new FirebaseSimpleLogin(new Firebase("firebaseURL"), function(error, user) {
if (error) {
} else if (user) {
// angular ngCookies service
$cookies.user = args.user.email;
} else {
}
});
To store all the todos per user, I'm simply storing his email ID against each todo. The problem with this approach is that I can modify the cookie replacing with someone else's email then I could see their todos.
Is there a way to know who has logged in using Firebase simple login instead of looking at the cookie? Is there any better way?
You can use angularFireAuth, which will bind a model to user authentication state:
function MyController($scope, angularFireAuth) {
var ref = new Firebase("https://<my-firebase>.firebaseio.com/");
angularFireAuth.initialize(ref, {scope: $scope, name: "user"});
}
$scope.user will then be null if the user is logged out, and set to a user object when the user is logged in. Learn more at http://angularfire.com/documentation.html#authentication

Resources