Login is successful even if it is invalid user - flutter

I simply want to accept username and password while login and check in the database if user is valid or not but the problem is for any username and password it shows "login successful". Whatever values I give it shows login successful but it should show "user doesnt exist." Please help me.
db_service.dart
Future<RegisterUser> getLogin(String user, String password) async {
await DB.init();
var res = await DB.rawQuery("userDetails WHERE emailId = '$user' and password = '$password'");
if (res.length > 0) {
return RegisterUser.fromMap(res.first);
}
return null;
}
UserLogin.dart (Code for the login button)
bool validateAndSave() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
void _submit(){
final form = _formKey.currentState;
var res;
if (validateAndSave()) {
setState(() {
res=dbService.getLogin(_email, _password).then((value) {
if(res!=0){
FormHelper.showMessage(
context,
"Login",
"Login Successfull",
"Ok",
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => People_List(),
),
);
},
);}
else {
FormHelper.showMessage(
context,
"Login",
"Login not Successfull",
"Ok", () {}
);
}
});
});
}
}

It seems you are using the Future function in the wrong way.
res= await dbService.getLogin(_email, _password);
if(res != 0){
} else {
}
Or
dbService.getLogin(_email, _password).then((value) {
if(value != 0){
}else {
}
}, onError(e){});

Related

Flutter App data is not being stored to Cloud firestore but images are being uploaded on fire storage

I am creating a app with user registration and firebase. when i hit the submit button neither my data saved to the firebase cloud data base nor the popup box pushes off but picture which the user tries to get in the profile uploads on the cloud storage. Need your suggestions. I am sharing the code. All the dependencies are also added.
Future <void> formvalidation() async
{
if (imageXFile == null)
{
showDialog(
context: context,
builder: (c) {
return ErrorDialog
(message: "Please Select an Image",);
}
);
}
else if (passwordController.text == confirmPasswordController.text) {
if (confirmPasswordController.text.isNotEmpty && emailController.text.isNotEmpty && nameController.text.isNotEmpty && phoneController.text.isNotEmpty && locationController.text.isNotEmpty)
{
// start uploading image
showDialog(
context: context,
builder: (c){
return LoadingDialog(message:"Registration in process");
}
);
String filename = DateTime.now().millisecondsSinceEpoch.toString();
fStorage.Reference reference = fStorage.FirebaseStorage.instance.ref().child("sellers").child(filename);
fStorage.UploadTask uploadTask = reference.putFile(File(imageXFile!.path));
fStorage.TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() {});
await taskSnapshot.ref.getDownloadURL().then((url) {
sellerImageurl = url;
authenticateAndSignUp();
});
}
else {
showDialog(
context: context,
builder: (c) {
return ErrorDialog
(message: "Form is not complete",);
}
);
}
}
else
{
showDialog(
context: context,
builder: (c) {
return ErrorDialog
(message: "Password do not match",);
}
);
}
}
void authenticateAndSignUp() async
{
User? currentUser;
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
await firebaseAuth.createUserWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
).then((auth) {
currentUser = auth.user;
}).catchError((error){
Navigator.pop(context);
showDialog(
context: context,
builder: (c) {
return ErrorDialog(
message: error.message,
);
}
);
});
if (currentUser != null)
{
saveDataToFirestore(currentUser!).then((value) {
Navigator.pop(context);
Route newRoute = MaterialPageRoute(builder: (c) => const HomeScreen());
Navigator.pushReplacement(context, newRoute);
});
}
}

I want to add showSnackBar to feedback user for this case

This is my onSavedChange func for user Information updating. also where do i need to add toast/snackbar, i cannot figure it out please help.
void onSavedChange() async {
if (!_formKey.currentState!.validate()) {
return;
} else {
try {
loadingController.add(true);
final response = await userApi.changeUserInformation(
newEmail: textEditingControllerEmail.text.trim(),
newFirstName: textEditingControllerFirstName.text.trim(),
newLastName: textEditingControllerLastName.text.trim(),
);
printMe("response:$response");
await LocalStorage.saveUserData(firstName: response.firstName, lastName: response.lastName, email: response.email );
AppConstant.FIRST_NAME = await LocalStorage.read(key: LocalStorage.FIRSTNAME);
AppConstant.LAST_NAME = await LocalStorage.read(key: LocalStorage.LAST_NAME);
AppConstant.USER_EMAIL = await LocalStorage.read(key: LocalStorage.UER_EMAIL_KEY);
// printMe("data1 is ${AppConstant.FIRST_NAME}");
// printMe("data2 is ${AppConstant.LAST_NAME}");
// printMe("data3 is ${ AppConstant.USER_EMAIL}");
bool? isLoading = await Navigator.push(context, MaterialPageRoute(builder: (context) => const HomePage(startPageIndex: 4, )));
if (isLoading != null) {
loadingController.add(isLoading);
}
}
catch (error) {
isLoading.add(false);
UIHelper.showErrorMessageDialog(error, context);
}
}
}

onTap keeps getting called again and again

I had an onTap function for an InkWell with the following code:
onTap: () async {
setState(() {
hasPressedLogIn = true;
print(hasPressedLogIn);
});
var loginData = await lib.login(username, password);
print('got loginData');
setState(
() {
if (password == '' && username == '' ||
password == '' ||
username == '') {
loginText = 'username or password empty';
} else {
utils.saveLoginData(username, password, loginData!.token.session,
loginData.token.refresh);
print('saved login data');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(
token: loginData.token.session,
),
),
);
}
},
);
},
Now, the code executes perfectly for the first time and the app successfully navigates to the next page without any error, however the onTap function doesn't stop despite having done it's job resulting in the rate limit being exceeded. The function seems to loop around the line
var loginData = await lib.login(username, password);
which later on exceeds the login attempt limit. How am I supposed to stop these unnecessary calls?
Change it to this:
onTap: () async {
if (password == '' && username == '' || password == '' || username == '') {
setState(() {
loginText = 'username or password empty';
});
} else {
setState(() {
hasPressedLogIn = true;
});
print(hasPressedLogIn);
utils.saveLoginData(
username,
password,
loginData!.token.session,
loginData.token.refresh);
print('saved login data');
var loginData = await lib.login(username, password);
print('got loginData');
Navigator.push(context, MaterialPageRoute(
builder: (context) => HomePage( token: loginData.token.session,),),);}
},
onTap: () async {
if(hasPressedLogIn == false){
setState(() {
hasPressedLogIn = true;
print(hasPressedLogIn);
});
var loginData =
await lib.login(username, password);
print('got loginData');
setState(
() {
if (password == '' && username == '' ||
password == '' ||
username == '') {
loginText = 'username or password empty';
} else {
utils.saveLoginData(
username,
password,
loginData!.token.session,
loginData.token.refresh);
print('saved login data');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(
token: loginData.token.session,
),
),
);
}
},
);}
else{
Future.delayed(const Duration(milliseconds: 1500), () {
//after a limited duration you will be able to tap it again
setState(() {
hasPressedLogIn = false;
print(hasPressedLogIn);
});
});
}
},

NoSuchMethodError: Class 'FlutterError' has no instance getter 'code'. Receiver: Instance of 'FlutterError' Tried calling: code)

I've been trying a sample Flutter application code from GitHub to simply login and register the user on Firebase. Every time I login or register after clean building the application, it takes me to the main page but throws this exception Exception has occurred. NoSuchMethodError (NoSuchMethodError: Class 'FlutterError' has no instance getter 'code'. Receiver: Instance of 'FlutterError' Tried calling: code)
I've no idea what 'FlutterError' is referring to because I don't see any such class. and there are two occurrences of code in the file named 'login-register.dart'. I'm attaching the code below:
(Note: it runs okay after I hot reload the app and the user is already logged in, only throws exception the first time)
void _validateLoginInput() async {
final FormState form = _formKey.currentState;
if (_formKey.currentState.validate()) {
form.save();
_sheetController.setState(() {
_loading = true;
});
try {
final FirebaseUser user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: _email, password: _password)).user;
// final uid = user.uid;
Navigator.of(context).pushReplacementNamed('/home');
} catch (error) {
switch (error.code) {
case "ERROR_USER_NOT_FOUND":
{
_sheetController.setState(() {
errorMsg =
"There is no user with such entries. Please try again.";
_loading = false;
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(errorMsg),
),
);
});
}
break;
case "ERROR_WRONG_PASSWORD":
{
_sheetController.setState(() {
errorMsg = "Password doesn\'t match your email.";
_loading = false;
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(errorMsg),
),
);
});
}
break;
default:
{
_sheetController.setState(() {
errorMsg = "";
});
}
}
}
} else {
setState(() {
_autoValidate = true;
});
}
}
void _validateRegisterInput() async {
final FormState form = _formKey.currentState;
if (_formKey.currentState.validate()) {
form.save();
_sheetController.setState(() {
_loading = true;
});
try {
final FirebaseUser user = (await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: _email, password: _password)).user;
UserUpdateInfo userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = _displayName;
user.updateProfile(userUpdateInfo).then((onValue) {
Navigator.of(context).pushReplacementNamed('/home');
Firestore.instance.collection('users').document().setData(
{'email': _email, 'displayName': _displayName}).then((onValue) {
_sheetController.setState(() {
_loading = false;
});
});
});
} catch (error) {
switch (error.code) {
case "ERROR_EMAIL_ALREADY_IN_USE":
{
_sheetController.setState(() {
errorMsg = "This email is already in use.";
_loading = false;
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(errorMsg),
),
);
});
}
break;
case "ERROR_WEAK_PASSWORD":
{
_sheetController.setState(() {
errorMsg = "The password must be 6 characters long or more.";
_loading = false;
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(errorMsg),
),
);
});
}
break;
default:
{
_sheetController.setState(() {
errorMsg = "";
});
}
}
}
} else {
setState(() {
_autoValidate = true;
});
}
}
The exception you're catching doesn't have a code property. That only exists with the firebase exception implementation, not the general exception class.
If you expect a certain type of error, you should explicitly catch that error and handle it properly and have a separate catch block for all other errors.
This can be done with an on ... catch block:
try {
final FirebaseUser user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: _email, password: _password)).user;
// final uid = user.uid;
Navigator.of(context).pushReplacementNamed('/home');
} on FirebaseAuthException catch (error) {
...
} catch(e) {
...
}
The methods you're calling in the code you shared will throw FirebaseAuthExceptions as shown in the code above.
You are getting an error that is not a FirebaseError but a FlutterError. This means, it does not implement a code field.
You can simply put
if(!(error is FirebaseError)){
print(error.message); // this is the actual error that you are getting
}
right below catch(error) { (in both files) to handle this.
However, it seems like you get another Flutter Error that you might want to handle. It should be printed to the console now.

How to do autologin with three diffrent userTypes in flutter and firebase?

I have this app that do login with firebase auth and firestore to get the userType, This code is written obviously in the login page, What I want to add is autologin ASA the app runs which firebase offers with the correct userType So the first proplem how to transfer the email value to the main.dart page as I search in the firestore with the email to get the userType, Second proplem is that When I tried to do auto login in the login page with three different userTypes It does login but not auto login
CODE :
#override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then(
(result) {
if (result != null) {
if (userType == 'userType1') {
Navigator.pushReplacementNamed(context, '/userType1page');
}
if (userType == 'userType2') {
Navigator.pushReplacementNamed(context, '/userType2page');
}
if (userType == 'userType3') {
Navigator.pushReplacementNamed(context, '/userType3page');
}
}
So Here It gets the user But no auto login, what I observed that When U remove the other IFs inside the big if and do 1 Navigation It works So don't know what to do, Please Help me I asked three questions before and didn't get an answer.
PS : NEW TO FLUTTER :)
#FLUTTER_FOREVER
Getting user Data from firestore:
void getUserData() async {
try {
firestoreInstance
.collection('Users')
.document(usernameController.text)
.get()
.then((value) {
setState(() {
email = (value.data)['email'];
password = (value.data)['password'];
gender = (value.data)['gender'];
username = (value.data)['username'];
userType = (value.data)['userType'];
});
});
} catch (e) {
print(e.toString);
}
}
Logining in :
void login() async {
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
firebaseAuth
.signInWithEmailAndPassword(
email: emailController.text, password: passwordController.text)
.then((result) {
{
if (userType == 'Student') {
Navigator.pushReplacementNamed(context, '/StudentsPage');
} else if (userType == 'Teacher') {
Navigator.pushReplacementNamed(context, '/TeacherPage');
} else if (userType == 'Admin') {
Navigator.pushReplacementNamed(context, '/AdminPage');
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text(
'Please make sure that you have an internet connection '),
actions: [
FlatButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
}
}
I found the answer I must identify the var userType inside the initState and It worked by using the getUserData() function but I had a problem I can't use usernameController because It's a var and I didn't defined it so any idea how to get the userType with the document reference usernameController Which I can't identify X-( 'R.I.P #omardeveloper'