I am developing an android App in which I implemented Firebase realtime database. And now I want to login using by email id and password which stored in database. I know firebase auth can be use for authentication but I want to login using realtime database like we do in Sql or my sql.
问题:
回答1:
I done this. First I fetch data of particular email id from database and than compare its password and assign the related function to do..
Query query = databaseReference.child("users").orderByChild("email").equalTo(txvUsername.getText().toString().trim());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot user : dataSnapshot.getChildren()) {
// do something with the individual "issues"
UsersBean usersBean = user.getValue(UsersBean.class);
if (usersBean.password.equals(txvPassword.getText().toString().trim())) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(context, "Password is wrong", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(context, "User not found", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thanks..
回答2:
I am assuming that you know how to use ValueEventListener, onDataChange method and Datasnapshot.
As you stated above, you want to do it like in SQL or MySQL. So instead of using email, I will use username and password.
You can authenticate your user without using Firebase Authentication. However, this is not recommended for the database security.
{
"userList": {
"JRHTHaIsjNPLXOQivY": {
"userName": "userA",
"password": "abc123"
},
"JRHTHaKuIFIhnj02kE": {
"userName": "userB",
"password": "abc123"
}
},
"userAuth": {
"userA": "JRHTHaIsjNPLXOQivY",
"userB": "JRHTHaKuIFIhnj02kE"
}
}
As you can see above I have saved the the userName and userId in firebase db. When a user enter the username and password, you should read the userId by using username in the userAuth. Once you have retrieved the userID, use it to access the userList for the user details. This is where you check for the entered password.
{
"userList": {
"userA": {
"password": "abc123"
},
"userB": {
"password": "abc123"
}
}
}
Or you can just authenticate your users like this.