Flutter Firebase phone Auth not catching errors - flutter

I am using phone authentification with OTP codes with flutter.
My code:
checkPin(String pin) async {
setState(() {
checkingPin = true;
});
UserCredential? response;
try {
PhoneAuthCredential? credential = PhoneAuthProvider.credential(
verificationId: verificationCode, smsCode: pin);
response = await FirebaseAuth.instance.signInWithCredential(credential);
} on FirebaseAuthException catch (err) {
print(err);
} on FirebaseException catch (err) {
print(err);
} on PlatformException catch (err) {
print(err);
} catch (err) {
print(err);
}
When purposely entering te wrong code, it throws a PlatformError. Despite me catching multiple errors (including PlatformError) in the ty catch block.
The error reads:
PlatformException (PlatformException(invalid-verification-code, The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code SMS and be sure to use the verification code provided by the user., {code: invalid-verification-code, message: The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code SMS and be sure to use the verification code provided by the user., nativeErrorMessage: The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code SMS and be sure to use the verification code provided by the user., nativeErrorCode: 17044, additionalData: {}}, null))
I do not understand why it crashes the app rather than catching the error, when i explicity try to catch PlatformExceptions. My firebase_auth package version is :^3.3.5.

Related

signInWithCredential returns null without any error in flutter

I'm using Firebase to sign in with phone number it does send OTP message but when I'm trying to sign with credentials using the OTP I got and the verification ID (they're not null they do have values) it returns null here (result is null) not throwing any errors
here's my code
static Future<UserCredential?> verifyOTP(
String verificationId, String otp) async {
UserCredential? result;
try {
print(otp);
print(verificationId);
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: otp,
);
result = await _firebaseAuth?.signInWithCredential(credential);
User? user = _firebaseAuth?.currentUser;
print('user $user');
print('results $result');
} on FirebaseAuthException catch (error) {
print(error);
}
return result;
}
By signInWithCredential do you mean Email and Password Firebase Authentication?
If so you should use signInWithEmailAndPassword Firebase Auth method.
Example below:
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
} catch (_) {
throw const LogInWithEmailAndPasswordFailure();
}

Is there any error in the try-catch exception handling below?

I tried to handle an exception while a user is trying to login after being authenticated by firebase. But this try-catch is not working in my flutter project.
Can someone let me know where did i go wrong? I have attached my code below.
Thank you in advance.
class AuthService {
//Creating an instance of firebase.
final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
User? _userFromFirebase(auth.User? user) {
if (user == null) {
return null;
}
return User(user.uid, user.email);
}
Stream<User?>? get user {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
Future<User?> signInWithEmailAndPassword(
String email,
String password,
) async {
try {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
} on Exception catch (_, e) {
//I want to display a toast message if the login fails here.
print(e);
}
}
Future<void> signOut() async {
return await _firebaseAuth.signOut();
}
}
In your try-catch block you are catching Exception types, but Firebase Authentication has its own exception type, FirebaseAuthException.
For possible error codes for this specific sign-in see here, but there are others as well.
Check the following code:
try {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
} on FirebaseAuthException catch (e) {
// here you will have the different error codes in `e.code`
// for example `invalid-email` or `wrong-password`
}
It is up to you how do you handle these errors. You can return the error code for example and handle it from where you call this function (as h8moss suggested in comment).
And keep in mind that there are other possible reasons for a sign-in to fail than FirebaseAuthException. For example network connection can be down. So a more complete solution to catch other errors as well would be something like:
try {
// sign in
} on FirebaseAuthException catch (e) {
// handle Firebase Authentication exceptions
} catch (e) {
// handle other exceptions
}

Flutter google sign in id token invalid value

I am developing google sign in feature in flutter and i'm able to extract id token from auth header but when i try to hit google api token info endpoint with the id token it's giving invalid id token as response but the accessToken is still working which is comming from the same header. Can anyone please help me solve this issue?
This is the code i'm using for extracting id token
try {
_googleSignIn.signIn().then((result) {
print(result);
result!.authentication.then((googleKey) {
// print(googleKey.accessToken);
print(googleKey.idToken);
// print(_googleSignIn.currentUser!.displayName);
}).catchError((err) {
print('inner error');
});
}).catchError((err) {
print('error occured');
});
} catch (e) {
print(e);
}

Flutter FirebaseAuth: SignInWithEmailAndPassword unable to handle error when the email address is badly formatted

Here is my email sign in method in my FirebaseAuthService class:
#override
Future<UserCustom> signInWithEmail(
String emailAddress, String password) async {
try {
UserCredential _signInWithEmailAndPasswordGoogle = await _auth
.signInWithEmailAndPassword(email: emailAddress, password: password);
if (_signInWithEmailAndPasswordGoogle.user != null) {
return _userToUserModel(_signInWithEmailAndPasswordGoogle.user);
} else {
throw PlatformException(
code: 'SIGN_IN_INTERRUPTED', message: 'Sin in interrupted');
}
} on PlatformException {
print('Happened');
rethrow;
}
}
And here is where the exception should be handled:
// creating the submit function
Future<void> _submit(EmailSignInModelProviderPattern model) async {
// if it is on sign in use sign in function ELSE use register function
try {
await model.submit();
Navigator.pop(context);
} on PlatformException catch (e) {
CustomErrorPlatformException(
title: 'Sign in failed',
exception: e,
).show(context);
} catch(e){
print(e.toString());
}
}
And yet when I enter a badly formatted address the process is interrupted at message_codecs.dart file at the method dynamic decodeEnvelope(ByteData envelope){... line 572 with error message:
Exception has occurred. PlatformException
(PlatformException(firebase_auth,
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The
email address is badly formatted., {code: invalid-email,
additionalData: {}, message: The email address is badly formatted.}))
I couldn't figure out how to handle this exception, knowing that it never happened to me before upgrading to firebase_auth: ^0.18.0+1.
check this issues where it explains why is happens
https://github.com/FirebaseExtended/flutterfire/issues/1760
.
If you use an Emulator and change textfield with tab button then there's an extra space left behind on that email field ->*myemail#gmail.com *
to avoid this extra space you have to use .trim() method.
in your case
UserCredential _signInWithEmailAndPasswordGoogle = await _auth
.signInWithEmailAndPassword(email: emailAddress.trim(), password: password);
I guess this solves your problem.
I was having a similar issue, your code looks fine. Try disabling Uncaught Expectations in the Debugging panel for VScode solved the issue for me.
https://github.com/FirebaseExtended/flutterfire/issues/3303#issuecomment-687560133

Flutter local_auth dialog closes if authentication fails

I am using https://pub.dev/packages/local_auth library to implement local_auth in my app.
I am using the following code to authenticate.
Future<void> _authenticate() async {
bool authenticated = false;
try {
authenticated = await auth.authenticateWithBiometrics(
localizedReason: 'Scan your fingerprint to authenticate');
print('Authentitcated: $authenticated');
} on PlatformException catch (e) {
print(e);
}
}
If authentication is success it shows Authenticated: true but it does not show anything if authentication fails. Also, the authentication dialogue closes automatically if authentication fails.
How do I return the authentication false status also keep the dialogue open even after authentication is failed?