Flutter Firebase : How to find all auth error codes? - firebase

I am using Flutter Firebase auth latest version and I am trying to sign up the user with :
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
The problem is e.code returns a string depending on the error and somehow I can not find all the error codes so I can do an exhaustive UI response. e.g user-not-found. How may I find all the error codes to include them in other if statements?

You can find the possible errors in the documentation for the Flutter firebase_auth package.
For instance, the createUserWithEmailAndPassword method has the following possible errors:
email-already-in-use: Thrown if there already exists an account with the given email address.
invalid-email: Thrown if the email address is not valid.
operation-not-allowed: Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console,
under the Auth tab.
weak-password: Thrown if the password is not strong enough.
It's the same for the other methods that throw errors.

Related

How to create a user in Firebase Auth with a custom UID? [duplicate]

This question already has answers here:
how to create FireBase new users with custom UID with flutter
(2 answers)
Closed 12 months ago.
How can I create a user in Firebase auth with a custom UID for me.
In my app, I am using Email and Password to create the users. So I also use the method:
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
Is there any way for me to provide the UID and keep better control of my users?
Something like (In the same method):
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
//uid: "My own id"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
What can I do here?
I don't believe you can do it via the FlutterFire SDK, but through the Firebase Admin SDK (i.e. via a Cloud Function), and if you do, you have to use the generated token to authenticate.
https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_the_firebase_admin_sdk
Alternative: Since Email and Password Authentication already give you a unique UID, that UID is pretty strong for any user management, but in case you want to come up with your own, you could generate another one (still keeping the one from Firebase Email and Pwd Auth - just for reference purposes) and when adding your users to another collection, you could do like:
FirebaseFirestore.instance.collection('users').add({
'uid': userCredential.user.uid,
'sUid': 'YOUR_GENERATED_ONE',
'email': 'email',
// other user info
});
Something of that nature. My two cents.

Flutter FirebaseAuth: SignUp unable to handle error when the email address is used by another user

My code here, and the error pointed at -> await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: email.trim(), password: password.trim()); - in code below
Future SignUp() async {
try {
UserCredential result = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: email.trim(), password: password.trim());
User user = result.user;
return user;
} on FirebaseAuthException catch (e) {
print(e);
if (e.code == 'email-already-in-use') {
setState(
() // setState rebuilds the entire build by modifying the code inside it
{
error = e.toString();
EmailExists =
true; //sets the emailExists variable to 'true' and rebuild
});
}
}
}
Error:
PlatformException (PlatformException(firebase_auth, com.google.firebase.auth.FirebaseAuthUserCollisionException: The email address is already in use by another account., {message: The email address is already in use by another account., additionalData: {}, code: email-already-in-use}, null))
By default Firebase Authentication only allows a single user to register with a specific email address in a project. When a second user tries to register with the same email address, you get the error that you have and you'll need to handle that scenario in your code. Typically you'll tell the user that the email address has already been registered and either ask them for their password, or tell them to use another email address.
If you want to allow multiple users to register with the same email address, you can enable that by changing the Multiple accounts per email address setting in the Sign-in methods pabel of the Firebase console.

How to detect firebase user registration and signIn successfully in flutter

As per the documentation of FlutterFire, there are two different methods for signIn and signUp for email and password authentication.
For signUp
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
For signIn
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
By this code I can handle error by FirebaseAuthException and stop some loading progress. But how do I detect that user successfully register and do something as per success registration?
But how do I detect that user successfully register?
It is actually detailed in the documentation section that explains the code you mention in your question.
In particular, for registration the doc says:
The method is a two-step operation; it will first create the new
account (if it does not already exist and the password is valid) and
then automatically sign in the user in to that account. If you are listening to changes in authentication state, a new event will be
sent to your listeners.
To listen to changes in authentication state you can call the authStateChanges() method on your FirebaseAuth instance, as follows:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
// !!!!! Here you know the user is signed-in !!!!!
print('User is signed in!');
}
});
For signIn, it is the same. The doc states that:
Once successful, if you are listening to changes in authentication
state, a new event will be sent to your listeners.
Refer to the registration case above.
So, in summary, on one hand you call the methods to either register (createUserWithEmailAndPassword()) or sign-in (signInWithEmailAndPassword()) and, on the other hand, you set a listener that listens to changes in authentication state. The listener alerts you when the call to one of the two methods is successful.
The on FirebaseAuthException catch (e) {...} blocks deals with the cases when the call to one of the two methods is not successful.
Finally, note the following article from the Firebase Developers Medium publication: it presents a slightly different approach, declaring async methods which check if the user object returned by the methods is null or not, and call setState() accordingly.
For example:
void _register() async {
final FirebaseUser user = (await
_auth.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
)
).user;
if (user != null) {
setState(() {
_success = true;
_userEmail = user.email;
});
} else {
setState(() {
_success = true;
});
}
}

what are the error codes for Flutter Firebase Auth Exception?

I have tried to read this thread List of Authorisation errors with Firebase login , and also I have tried to search, but I just can find admin SDK authentication error in here here
those error code from those links are different from the error code for Firebase Auth for Flutter app
I mean, I need the error codes in here
Future<void> signInUsingEmail({required String email, required String password}) async {
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (error) {
// I need the error.code in here
print(error.code);
}
could I know all available error codes? so I can write my own error message in my own language. as for now, I can only catch these error codes below
"too-many-requests"
"wrong-password"
"network-request-failed"
what else?
For the signInWithEmailAndPassword method for Flutter, you will find the error codes in the firebase_auth package documentation.
They are actually the same than the JS SDK ones: https://firebase.google.com/docs/reference/js/firebase.auth.Auth#error-codes_12
For anyone that does not like clicking on links:
signInWithEmailAndPassword
wrong-password: Thrown if the password is invalid for the given email, or the account corresponding to the email doesn't have a password set.
invalid-email: Thrown if the email address is not valid.
user-disabled: Thrown if the user corresponding to the given email has been disabled.
user-not-found: Thrown if there is no user corresponding to the given email.
createUserWithEmailAndPassword
email-already-in-use: Thrown if there already exists an account with the given email address.
invalid-email: Thrown if the email address is not valid.
operation-not-allowed: Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.
weak-password: Thrown if the password is not strong enough.
signInWithCredential
account-exists-with-different-credential: Thrown if there already exists an account with the email address asserted by the credential. Resolve this by calling fetchSignInMethodsForEmail and then asking the user to sign in using one of the returned providers. Once the user is signed in, the original credential can be linked to the user with linkWithCredential.
invalid-credential: Thrown if the credential is malformed or has expired.
operation-not-allowed: Thrown if the type of account corresponding to the credential is not enabled. Enable the account type in the Firebase Console, under the Auth tab.
user-disabled: Thrown if the user corresponding to the given credential has been disabled.
user-not-found: Thrown if signing in with a credential from EmailAuthProvider.credential and there is no user corresponding to the given email.
wrong-password: Thrown if signing in with a credential from EmailAuthProvider.credential and the password is invalid for the given email, or if the account corresponding to the email does not have a password set.
invalid-verification-code: Thrown if the credential is a PhoneAuthProvider.credential and the verification code of the credential is not valid.
invalid-verification-id: Thrown if the credential is a PhoneAuthProvider.credential and the verification ID of the credential is not valid.id.
reauthenticateWithCredential
user-mismatch: Thrown if the credential given does not correspond to the user.
user-not-found: Thrown if the credential given does not correspond to any existing user.
invalid-credential: Thrown if the provider's credential is not valid. This can happen if it has already expired when calling link, or if it used invalid token(s). See the Firebase documentation for your provider, and make sure you pass in the correct parameters to the credential method.
invalid-email: Thrown if the email used in a EmailAuthProvider.credential is invalid.
wrong-password: Thrown if the password used in a EmailAuthProvider.credential is not correct or when the user associated with the email does not have a password.
invalid-verification-code: Thrown if the credential is a PhoneAuthProvider.credential and the verification code of the credential is not valid.
invalid-verification-id: Thrown if the credential is a PhoneAuthProvider.credential and the verification ID of the credential is not valid.
signInWithAuthProvider
user-disabled: Thrown if the user corresponding to the given email has been disabled.
signInAnonymously
operation-not-allowed: Thrown if anonymous accounts are not enabled. Enable anonymous accounts in the Firebase Console, under the Auth tab.
signInWithEmailLink
expired-action-code: Thrown if OTP in email link expires.
invalid-email: Thrown if the email address is not valid.
user-disabled: Thrown if the user corresponding to the given email has been disabled.
So I created this gist
And it's basically a handler for some common firebase auth exceptions.
This is an example on how to use it
Future createUser(String email, String password) async {
try {
UserCredential customUserCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: email, password: password);
return customUserCredential.user!.uid;
} on FirebaseAuthException catch (authError) {
throw CustomAuthException(authError.code, authError.message!);
} catch (e) {
throw CustomException(errorMessage: "Unknown Error");
}
TextButton(
onPressed: () async {
try {
//final user = FirebaseAuth.instance.currentUser;
final email = _emailController.text;
final password = _passwordController.text;
// await FirebaseAuth.instance // final userCredential =
// .signInWithEmailAndPassword(
// email: email, password: password);
AuthService.firebase()
.logIn(email: email, password: password);
final user = AuthService.firebase().currentUser;
if (user?.isEmailVerified ?? false) {
Navigator.of(context).pushNamedAndRemoveUntil(
emailRoute, (route) => false);
} else {
Navigator.of(context)
.pushNamedAndRemoveUntil(noteRoute, (route) => false);
}
//devtools.log(userCredential.toString());
//This line of text may not work to print data
// print(userCredential.toString());
} on FirebaseAuthException catch (e) {
if (e.code == 'network-request-failed') {
showErrorDialog(context, 'No Internet Connection');
//devtools.log('No Internet Connection');
} else if (e.code == "wrong-password") {
return showErrorDialog(
context, 'Please Enter correct password');
//devtools.log('Please Enter correct password');
//print('Please Enter correct password');
} else if (e.code == 'user-not-found') {
showErrorDialog(context, 'Email not found');
// print('Email not found');
} else if (e.code == 'too-many-requests') {
return showErrorDialog(
context, 'Too many attempts please try later');
//print('Too many attempts please try later');
} else if (e.code == 'unknwon') {
showErrorDialog(
context, 'Email and password field are required');
//print('Email and password field are required');
} else if (e.code == 'unknown') {
showErrorDialog(
context, 'Email and Password Fields are required');
//print(e.code);
} else {
print(e.code);
}
}
},
child: const Text('Login')),

How to properly catch exception from FirebaseAuthException

My Editor(Vs code) keeps catching this exception even when it's already caught in my code. And the code works fine after the exception is caught.
The exception Log
" Exception has occurred. PlatformException
(PlatformException(firebase_auth,
com.google.firebase.auth.FirebaseAuthUserCollisionException: An
account already exists with the same email address but different
sign-in credentials. Sign in using a provider associated with this
email address., {code: account-exists-with-different-credential,
additionalData: {authCredential: {providerId: facebook.com,
signInMethod: facebook.com, token: 0000000}, email: #######gmail.com},
message: An account already exists with the same email address but
different sign-in credentials. Sign in using a provider associated
with this email address.}, null)) "
My Facebook Login Code
Future<void> logInWithFaceBook() async {
try {
final FacebookLoginResult result = await _facebookLogin.logIn(['email']);
final fbToken = result.accessToken.token;
if (result.status == FacebookLoginStatus.loggedIn) {
final facebookCredential =
firebase_auth.FacebookAuthProvider.credential(fbToken);
await _firebaseAuth.signInWithCredential(facebookCredential);
}
} on firebase_auth.FirebaseAuthException catch (e) {
await fbLinkPendingCredential(e);
}
}

Resources