Cant register FireBase user from Flutter - flutter

I am unable to register an user from my app written in Flutter. I am also unable to get some form for error message. I can debug and see my createUser function is called and the arguments looks good. Nothing happens after I call "FirebaseAuth.instance.createUserWithEmailAndPassword". No exception and nothing is printed in the FireBase emulator console. What am I missing here? Here is what I got:
Emulator:
Running on 127.0.0.1:9099
main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
try {
await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
} catch (e) {
// ignore: avoid_print
print(e);
}
runApp(
MaterialApp(
title: "Foo",
home: buildContent(),
),
);
}
Registration function:
void createUser() async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: nameController.text,
password: passwordController.text,
);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} 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);
}
}
Edit:
I keep getting this message when i call "createUserWithEmailAndPassword"
W/System (26859): Ignoring header X-Firebase-Locale because its value was null.

In your createUser() Function i think you're sending empty values to firebase
request parameters like this and try it again
void createUser(String name, String Password) async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: name,
password: password,
);
print("User Created Success);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} 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);
}
}

So after some trail and error I ended up adding:
android:usesCleartextTraffic="true"
To the manifest file:
...\my_project\android\app\src\main\AndroidManifest.xml
I am not sure I like the "fix" as I think the requests are sent unencrypted. A google search gives me this description:
Android 6.0 introduced the useCleartextTraffic attribute under application element in android manifest. The default value in Android P is “false”. Setting this to true indicates that the app intends to use clear network traffic

Related

Flutter web firebase auth signInWithPhoneNumber showing error "captcha-check-failed" in release mode

I'm facing a problem with Flutter Web Firebase Phone Auth Verification. In debug it is working well and showing me the reCaptcha. But when I host it through GitHub pages in release mode, it shows an error "captcha-check-failed". Even the capcha isn't showing in release mode.
The signInWithPhoneNumber function:
Future<void> loginWithPhoneRequestOTPWeb(
WidgetRef ref,
GlobalKey<FormState> formKey,
String phoneNumber,
) async {
try {
EasyLoading.show();
await FirebaseAuth.instance
.signInWithPhoneNumber(
phoneNumber,
RecaptchaVerifier(
container: 'recaptcha',
size: RecaptchaVerifierSize.compact,
theme: RecaptchaVerifierTheme.dark,
onError: (e) {
print(e);
EasyLoading.showError(e.message!);
return;
},
onExpired: () {
print('Expired');
EasyLoading.showError('Session Expired');
return;
},
onSuccess: () {
EasyLoading.dismiss();
print('Captcha Success');
},
),
)
.then((ConfirmationResult result) {
// update the verificationphone provider
ref.read(sendOtpProvider(formKey).state).update((_) => true);
ref.read(confirmationResultProvider(formKey).state).update((_) => result);
EasyLoading.showSuccess(t!.otpSentSuccessfully);
});
} on FirebaseAuthException catch (e) {
if (e.code == 'invalid-phone-number') {
print('The provided phone number is not valid.');
EasyLoading.showError('The provided phone number is not valid.');
} else if (e.code == 'too-many-requests') {
print(
'You have exceeded the number of attempts allowed for this operation.');
EasyLoading.showError(
'You have exceeded the number of attempts allowed for this operation.');
} else {
print(e.code.toString());
EasyLoading.showError(e.code.toString());
}
} catch (e) {
print(e.toString());
EasyLoading.showError(e.toString());
}
}
I've tried without the RecaptchaVerifier as it is optional parameter.
Error Screenshot:
If I've missed anything please let me know. Thank You :)
Okay, I've figure out my problem. In the firebase authentication section, there is an "Authorized domains" section. Here I've to add my domains. But firebase only takes .com domains. As a result, I used firebase hosting and it is working fine

error : display a red line under this statement _userFromFirebaseUser(userCredential.user);

hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
return userCredential != null
? UserModel(
id: userCredential.uid,
bannerImageUrl: '',
name: '',
email: '',
profileImageUrl: '')
: null;
}
Stream<UserModel?> get userCredential {
return auth
.authStateChanges()
.map((userCredential) => _userFromFirebaseUser(userCredential!));
}
Future SignUp(email, password) async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
print("valid");
formdata.save();
try {
UserCredential userCredential =
(await auth.createUserWithEmailAndPassword(
email: myemail!, password: mypassword!));
FirebaseFirestore.instance
.collection('Users')
.doc(userCredential.user!.uid)
.set({'name': email, 'email': email});
_userFromFirebaseUser(userCredential.user);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Navigator.of(context).pop();
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Navigator.of(context).pop();
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
} else {}
}
and the red line appears on this line _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me
userCredential.user is User? not User
change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
return ....
}

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
}

Firebase authentication! I'm able to move to home page even if i enter a non registered user

I've successfully added firebase to my flutter2.0 project. I've enables authentication also.I'm able to register a new user also. But the logic to move to home page after authentication is not working. I'm able to login even if I enter a wrong user. I want if I enter proper user then I should navigate to home page, but if the user is not registered it one should not be able to navigate to next page. ie..the basic use of authentication.
But it's not happening here. I'm able to navigate to next place even if I enter wrong user.
Future signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
password:password,
);
} 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.');
}
}
}
Future newAccount(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} 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.toString());
}
}
}
//this is how I can this function and try to navigate to next page.
void logMeIn() {
if (formKey.currentState!.validate()) {
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();
}));
});
}
}**strong text**
signInWithEmailAndPassword returns a UserCredential object.
In your logic, you are using .then((value) {...etc})
This value is the result of signInWithEmailAndPassword.
Try changing your logic to this:
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
if(value.user ==null) return "Error in authentication"; // this will prevent your function form going further down the navigation if the usercredential doesn't have a valid user.
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();

Issues with code deprecation saving user info to firebase database

I have codes from former or deprecated flutter version on saving user info to firebase database.
But i have been trying to upgraded the code to the latest firebase_auth package but 'FirebaseUser' is flagged as an error.
void registerUser() async{
final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text).catchError((ex){
//Check Error and display message
PlatformException thisEx = ex;
showSnackBar(thisEx.message);
})).user;
// check if user registration is successful
if(user != null){
DatabaseReference newUserRef = FirebaseDatabase.instance.reference().child('users/${user.uid}');
Map userMap = {
'fullname': fullNameController.text,
'email': emailController.text,
'phone': phoneController.text,
};
newUserRef.set(userMap);
Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false);
}
}
I have tried upgrading the codes my self but, it doesn't look and behave like before. here is my code but i need some help.
Thanks in advance...
void registerUser() async{
//final UserCredential user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text));
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
if (userCredential != null) {
DatabaseReference newUserRef = FirebaseDatabase.instance.reference()
.child('users/${userCredential.toString}');
M
}
}
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);
}
}