I want users to type their email and password. After Authentication, based on their email I want to check whether they are admin or not and open different activities thereafter. How should I perform the search query? Is it even possible?
Below is the answer which worked for me. For general see Alex answer.
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
rootRef.collection("Users").whereEqualTo("Email","ashish#gmail.com").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.getString("Admin").equals("Yes")) {
Toast.makeText(Login.this, "Logged In!", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(Login.this, MainActivity.class));
} else {
Toast.makeText(Login.this, "Logged In!", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(Login.this, nonadmin.class));
}
}
} else {
mProgressBar.setVisibility(View.GONE);
Toast.makeText(Login.this, "Sign In Problem", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
To solve this, please use the following code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("Users").whereEqualTo("Email", "ashish#startup.com").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.getString("Admin").equals("Yes")) {
Log.d(TAG, "User is Admin!");
}
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
The output will be: User is Admin!.
Don't also forget to set your security rules like this:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
Related
I don't know if the problem is from the code. After signing up, when i try to log in, it shows "Wrong Credentials or Bad Connection! Try Again", which is the error to be called if the password is wrong or the email id is wrong.
firebaseAuth.signInWithEmailAndPassword(id,pass).addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String id=editID.getEditText().getText().toString().trim()+"#gmail.com";
db.collection("User").whereEqualTo("email",id).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
User obj=new User();
for(QueryDocumentSnapshot doc:queryDocumentSnapshots)
obj=doc.toObject(User.class);
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<String> task) {
try {
String token = task.getResult();
Log.e("DeviceToken = ",token);
}catch (Exception e){
e.printStackTrace();
}
}
});
db.document("User/"+firebaseAuth.getCurrentUser().getEmail()).update("fcmToken",SharedPref.getInstance(getApplicationContext()).getToken())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SignInActivity.this, "Registered for Notifications Successfully !", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this, "Registration for Notifications Failed !\nPlease Sign in Again to Retry", Toast.LENGTH_SHORT).show();
}
}
});
If a Task fails, it contains an exception with additional information in why it failed. You should log that exception:
db.document("User/"+firebaseAuth.getCurrentUser().getEmail()).update("fcmToken",SharedPref.getInstance(getApplicationContext()).getToken())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SignInActivity.this, "Registered for Notifications Successfully !", Toast.LENGTH_SHORT).show();
}
else
{
// 👇
Log.e("Auth", "Registration for Notifications Failed", task.getException());
Toast.makeText(SignInActivity.this, "Registration for Notifications Failed !\nPlease Sign in Again to Retry", Toast.LENGTH_SHORT).show();
}
}
});
Once you get the exception, search for the error message to see if others have dealt with the problem before.
I am developing an android app and using firebase database. It contains authorization and few activities for different roles. If you are entering as "Installer" opens one activity and if as "Contact-Centre" - another, but now it's not important. So I need to check a role of entered pair of email and password. So what I should to do?
Here is my database structure:
Sign in code:
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Аутентификация прошла успешно",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),RoleInstallerForm.class));
}
else {
Toast.makeText(MainActivity.this,"Проверьте правильность введённых данных", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
}
}
});
Modify your code to this:
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Àóòåíòèôèêàöèÿ ïðîøëà óñïåøíî",Toast.LENGTH_SHORT).show();
try {
currentUserUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}catch (Throwable throwable){
throwable.printStackTrace();
}
roleRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserUID).child("Role");
roleRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
String userRole = dataSnapshot.getValue().toString();
//Add if-else here if you need any
//For example:
//I DONT UNDERSTAND RUSSIAN ROLE YOU TYPE
// JUST REPLACE THE ROLE NAMES
if(userRole.equals(leader)){
startActivity(new Intent(MainActivity.this, some-activity.class));
}else{
startActivity(new Intent(MainActivity.this, other-activity.class));
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this,"Ïðîâåðüòå ïðàâèëüíîñòü ââåä¸ííûõ äàííûõ", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
}
}
});
So, I'm using Firebase Cloud and I have three references that I go through until I get my data.
this issue made me create 3 anonymous nested classes- which looks horrible, hard to follow and probably hard code to maintain.
I've added that code, I hope for your advice - how should I clean it up?
db.collection("users").document(mAuth.getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
Thanks in advance!
you can try something like this :
db.collection("users").document(mAuth.getUid())
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
callback1(document);
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
private void callback1(DocumentSnapshot document)
{
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback2();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void callback2(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback3();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
}
private void callback3(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
}
I am trying to add new fields to an already created document under "users" collection in firestore database.
From first activity I added basic information like name and description and gender to the firestore database (collection("users").document(uid)) and it worked. But when I am trying to add new fields (from second activity) to the same document it is not working. I tried to use set, SetOptions.merge, update, but nothing is working. Even I tried to add new collection then also it is not working. Can someone please help me to figure this out. Thanks in advance.
My codes are below from both the activities.
First Activity (BasicInfo.java) (working)
String uid = user.getUid();
Map<String, Object> dataToSave = new HashMap<>();
dataToSave.put(NAME, nameText);
dataToSave.put(ABOUT, aboutText);
dataToSave.put(GENDER, userGender);
db.collection("users").document(uid).set(dataToSave).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent userPreIntent = new Intent(BasicInfo.this, UserPre.class);
startActivity(userPreIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
});
Second Activity (UserPre.java) (Not working)
Map<String, Object> data = new HashMap<>();
data.put(STYLE, styleBeauty);
data.put(HUMOR, humor);
data.put(FITNESS, fitness);
data.put(TRAVEL, travel);
data.put(PHOTOGRAPHY, photography);
data.put(MUSIC, music);
data.put(DANCE, dance);
data.put(ART, art);
data.put(FASHION, fashion);
String uid = user.getUid();
db.collection("user").document(uid).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Data Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
});
You can add a FailureListener and it will tell you what's wrong in logcat.
db.collection("user").document(uid).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Data Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
I am new to Firebase development. I am creating a user login system with Firebase. I am struggling with verifying emails registered users. Here is the code I wrote.
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(MainActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("Success", "Yes");
}
else{
Log.i("Success", "No");}
}
});
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, Activity2.class));
finish();
}
}
});
}
});
EDIT: No verification email is triggered when sign up is successful. The error I am getting is
10-12 10:41:47.579 10529-10529/com.firebase I/Success:
Nocom.google.firebase.FirebaseException: An internal error has
occurred. [ USER_NOT_FOUND ]
You need to check the status of createUserWithEmailAndPassword() to ensure that it is successful before getting the current user and calling sendEmailVerification(). There are a number of reasons why createUserWithEmailAndPassword() might fail (account already exists, weak password, malformed email address, etc.). When it does fail, the current user with be the previously signed-in user or null, if there has not been a previous sign-in.
Restructure your code like this:
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(MainActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("Success", "Yes");
}
else{
Log.i("Success", "No");}
}
});
startActivity(new Intent(MainActivity.this, Activity2.class));
finish();
}
}
});
You need to Enable Email & Password Authentication, Configuring Email & Password
In this page you can find many tutorials on the page.
If you are using the new version of firebase, you could try to check your connection... Info here