Reload firebase user every time user open apps - android

I am making an app where if I delete users from the console user still can access some information from the database. so I reload the user every time users open the apps on the splash screen.
My concern is if it is a good idea or not to reload user every time opening the apps?
this is my current code is,
void reloadUserInfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
user.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
goToHome();
} else {
Helper.customToast(Splash.this, task.getException().getMessage());
goToLogin();
}
}
});
else
goToLogin();
}

I don't see that there is a problem here. If you're observing a specific issue, please post a question that describes what's not working the way you expect.

Related

Firebase does not create new user

I am a newbie in Firebase. Recently I am trying to save users into Firebase but I can't. When I generate the APK and run it onto the real device(Not Emulator), the new user does not add it into the Firebase. Also, no errors shown up. Task executed properly and go to OTPActivity. Here is my complete code:
public void saveUser()
{
firebaseAuth.createUserWithEmailAndPassword(emailAddress.getText().toString(),password.getText().toString()).addOnCompleteListener(ChatUserSignUpActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser user = firebaseAuth.getCurrentUser();
Intent intent = new Intent(ChatUserSignUpActivity.this, OTPActivity.class);
intent.putExtra("phoneNum",emailAddress.getText().toString());
startActivity(intent);
}
else
{
Toast.makeText(ChatUserSignUpActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Please help me. Thanks in advance.
When you authenticate your users with email and password, no data is saved into Firestore, nor in the Realtime Database. If you need to save the database in the database, you need to write code for that. So once your user is authenticated, you can get the data from the FirebaseUser object and write it to the database of your choice.

How to find if a user already exists when registering with OTP phone auth in firebase android?

I'm developing a social media application. In that, I need to check whether the user already exists or not when he login with otp (like in WhatsApp).
I have found similar questions like this in stackoverflow, but none of the questions have correct answer. Help me!
after a research, I found this answer.
In firebase, each phone number have a unique user id. So, if a user signs up from different devices, or reinstalls the application with a same phone number, he/she will get the same user Id. So with that, we can check our database like this:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final FirebaseUser user = task.getResult().getUser();
String uid = user.getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
final DocumentReference docRef = db.collection("users").document(uid);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(final DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
//redirect to home page
}
else{
//redirect to sign up page
}
}
Hope this will help someone :)
You can just use the admin SDK and lookup the user by phone number:
https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data
admin.auth().getUserByPhoneNumber(phoneNumber)
.then(function(userRecord) {
// User found.
})
.catch(function(error) {
// User not found.
});
If you try to create an user that already exists, Firebase will throw you an exception. You can handle that exception to do what you want.
Hope this helps!
First store the Firebase Phone Auth in FirebaseDatabase after every successful registration, then add a check when user try and enter the phone number if it already exist in database, If present then you got your answer otherwise register the user.
I hope the concept is clear. Will update you with the code soon.
#Soorya. If you want to make your application like WhatsApp then you have to simply authenticate the user using phone number and OTP. When the user gets verified successfully then check whether user details are available in Firebase Database or FireStore. If available then simply redirect the user to home screen otherwise redirect the user to the registration page. For that refer below code snippet.
mFirebaseAuth
.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
goToNextActivity(((AuthResult) task.getResult()).getUser());
return;
}
}
});
private void goToNextActivity(FirebaseUser firebaseUser) {
FirebaseDatabase
.getInstance()
.getReference()
.child("your table name")
.child("user id details")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot == null || dataSnapshot.getChildrenCount() <= 0) {
goToRegisterDetails(firebaseUser);
return;
}
User user = (User) dataSnapshot.getValue(User.class);
if (user == null
|| user.getUser_name() == null
|| user.getUser_name().isEmpty()
|| user.getUser_mobile() == null
|| user.getUser_mobile().isEmpty()) {
goToRegisterDetails(firebaseUser);
} else {
goToMainActivity(user);
}
}
public void onCancelled(DatabaseError databaseError) {
OTPVerificationActivity.this.hideProgressDialog();
Logger.e(databaseError.getMessage());
}
});
}
I hope that you will get your answer. You can easily achieve that you want to do in your application.

Firebase only authenticating on some devices?

I have tested this on my Moto G5+ (works) and Nexus 6 (doesn't work), and my firebase authentication only works on one of them:
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() == null) { //No existing user
mAuth.signInAnonymously().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v("myTag", "Cannot authenticate user" + e);
}
});
}
if(mAuth.getCurrentUser() != null) {
Log.v("myTag", "Boutta take photos");
takePhoto(this, 0);//back camera
}else{
Log.v("myTag", "Cannot take photos, user not authenticated");
}
What's odd is that I only get the log Cannot take photos, the user not authenticated, but not the log Cannot authenticate user. This means I am able to authenticate the user, but for some reason, it does not work
How come this only works on some devices?
Assuming your user starts off unauthenticated, once the first if statement is called and it attempts the anonymous sign in, that anonymous sign in happens asynchronously as it is waiting on a callback. So in that state the user isn't authenticated until the call back completes. The code then jumps to your second set of if/else statements where you check
mAuth.getCurrentUser() != null
but the callback for authentication still may have not returned, and your mAuth.getCurrentUser() is still null therefore jumping to the else statement and logging the Log.v("myTag", "Cannot take photos, user not authenticated");
Your callback may then return authenticating the user but at this point, its too late. You already run logic assuming the use wasn't authenticated.
#martinomburajr brought me to the right answer! Just to elaborate on his solution, in case anyone else has the same problem in the future, I needed to wait until the authentication was successful:
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() == null) { //No existing user
Log.v("myTag", "Boutta authenticate");
mAuth.signInAnonymously().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
}).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(mAuth.getCurrentUser() != null) {
//TAKE PHOTO HERE INSTEAD
takePhoto(c, 0);//back camera
}else{
Log.v("myTag", "Cannot take photos, user not authenticated");
}
}
});
}else {
Log.v("myTag", "aalready authenticated!");
takePhoto(c, 0);//back camera
frontOrBack = 0;
}
}
When I put my authentication-dependent code (in this case, to take a picture) I wasn't giving my app enough time to get a response from Firebase. Instead of just assuming that the user was authenticated, however, I fixed this issue by putting the authentication-dependent code in an OnCompleteListener. Many thanks to #martinomburajr for his helpful answer!

Detect if first auth via Facebook/Google

I am using Firebase Auth with the Facebook & Google login. After a successful login, I also register the user on my own server.
// facebook or google auth
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
registerOnServer(task);
}
});
That works fine the first time. But the second time the user logs in, my backend complains, because a user with those credentials already exists.
How can I detect if this is the first time a user logs in via one of the given providers? I can't use SharedPreferes, because they get erased after a user uninstalls the app, which leads to problems after reinstalling.
firebaseAuth.fetchProvidersForEmail(userEmail).
addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
List<String> providerList = task.getResult().getProviders();
if (providerList.isEmpty()) {
//Empty List means new user
}
else if (providerList.contains("facebook.com")) {
//Facebook is the provider
}
}
}
Use above code to get providers.

Android- How to upload image to Firebase under specific users

I am developing an app, and so far it's able to upload images, and register users.
However, these two functionalities run independent of each other. Ergo, I need to make it so that the images are saved under the user that uploads it. I am a novice Android programmer and just started learning about Firebase and could use the help.
In Registration process,
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email, email)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
android.util.Log.e("Firebase", "performFirebaseRegistration:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
AlertUtils.showAlert(MainActivity.this, getString(R.string.sign_up), task.getException().getMessage());
} else {
FirebaseUser firebaseUser = task.getResult().getUser(); // here you will get userDetails
}
}
});
From firebaseUser you can get user id by firebaseUser.getUid().
Once you upload the message,sent to realtime firebase b the user id as below,
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child(ARG_USERS)
.child(firebaseUser.getUid())
.child("image")
.setValue(<you image download url>);

Categories

Resources