I'm not going to paste any code because I receive the desired behavior when a user creates account with a phone number in firebase auth.
My problem is after an app update, firebaseUser.getCurrentUser is null despite the fact that the user is already signed up.
My question:
How do I mimic a behavior like WhatsApp which doesn't require the user to always go through OTP after every app update?
Iv tried using authState:
auth.addAuthStateListener(firebaseAuth -> {
user = firebaseAuth.getCurrentUser();
if(user == null)
signUp() });
Hoping after update user won't be null. But it's always null after updating the app.
Actually what I didn't realize is that I was trying to mimic an update behavior by installing and uninstalling the app. Turns out token credentials are lost in the process. I just assumed Firebase attaches to the device identity some how, some where. I admit I need some instruction
Related
I was using Firebase Auth Gmail Authentication. While doing some random tests on the app, I deleted the account from Firebase Auth Console while I was still logged in.
Now even if I uninstall the App and reinstall it, I still get the UID even though that UID is not present in the Firebase Auth Console. The first lines of code as soon as I open the app are as follows:
val uidz = FirebaseAuth.getInstance().currentUser?.uid.toString()
Log.d("uid as soon as i open the app",uidz)
Logcat Reads as
2022-09-27 21:40:01.802 23060-23060/com.example.alliaiseV1 D/uid as soon as i open the app: uZOs2XhBOrX4YU8qKem3lD4C7cy1
Strange parts:
This UID if I navigate to some other page and re-check the current user changes to null
Every time I uninstall and reinstall the App I see the same UID every time
It only happens on my device for every other device when I re-install the App the current UID returns as null but for my device, it returns as the above in logcat
Deleting App Data and Cache works but again if I reinstall I see the UID
I edited the code to :
val uidz = FirebaseAuth.getInstance().currentUser?.uid.toString()
Log.d("uid as soon as i open the app",uidz)
FirebaseAuth.getInstance().signOut()
Log.d("uidlogout", "${FirebaseAuth.getInstance().currentUser?.uid.toString()}")
The logcat I read for it is as follows :
2022-09-27 21:45:06.228 23964-23964/com.example.alliaiseV1 D/uid as soon as I open the app: uZOs2XhBOrX4YU8qKem3lD4C7cy1
2022-09-27 21:45:06.229 23964-23964/com.example.alliaiseV1 D/uidlogout: null
From where is this UID coming?
Why do I see the same UID every time?
How do I get rid of it?
While doing some random tests on the app, I deleted the account from Firebase Auth Console while I was still logged in. Now even if I uninstall the App and reinstall it, I still get the UID even though that UID is not present in the Firebase Auth Console.
If you accidentally deleted a user account from the Firebase console it doesn't mean that the current token automatically expires for that account. No, the current tokens will remain valid until it expires. If you however are interested in changing the expiration interval, please note that this option is available in your Firebase console.
If you want to force a user to sign out, then you can use FirebaseAuth#signOut() method, which:
Signs out the current user and clears it from the disk cache.
To prevent that from happening, you should consider creating authorization rules. In this way, you'll be able to differentiate users with valid tokens from the ones that have deleted accounts. If you are using, for example, the Realtime Database to keep a user's data, then you can check whether that user still exists in your security rules using the following line of code:
root.child('users').child(auth.uid).exists()
For more info, I recommend you read David East's answer in the following post:
Deletion of User in firebase does not trigger onAuth method
Sorry for the ambiguity in the question but it is actually quite a simple one.
When my android Application boots up I initialize AppCenter as follows:
AppCenter.start(
this, BuildConfig.APP_CENTER_SECRET,
Analytics::class.java, Crashes::class.java, Distribute::class.java
)
if(BuildConfig.FLAVOR != ApplicationVariants.ProductFlavors.PRODUCTION){
AppCenter.setLogLevel(Log.VERBOSE)
}
AppCenter.setUserId(UUID.randomUUID().toString())
Distribute.setUpdateTrack(UpdateTrack.PUBLIC)
Distribute.checkForUpdate()
However, when the user logs into the application I would like to set the UserId to the users email as follows once the user logs in:
JwtUtils.getIdentityTokenModel(requireContext())?.let {
AppCenter.setUserId(it.email)
}
Lastly when the user logs out I reset the user Id to a random guid. The reason for this is visibility on which user has which crash logs. This is a requirement from business.
However, in the app center crash logs, it seems the UserId never changes to the email even if an error occurs while the user is logged in.
My question is simple. Is there a restriction on how many times I am allowed to change the AppCenter User Id? I cannot seem to find it anywhere in the docs.
Thanks in advance
Please see these docs about userId API:
The value for the user ID is limited to 256 characters. It will be
shown with your crash reports but not used for aggregation or counts
of affected users. In case you set user ID multiple times, only the
last user ID will be used. You need to set the user ID yourself before
each application launch, because this value isn't stored by the SDK
between launches.
My app is not automatically logging in when I restart the Android emulator. I believe previously it was doing so - though this might have been a bug caused by some bad code I have since ironed out. So to troubleshoot this problem I first need to discover whether or not this is simply a feature of the emulator.
Here is my code. I've confirmed that it successfully logs into FirebaseAuth and creates a user. According to documentation, automatically logging in on reboot should be as easy as this:
#Override
public void onStart() {
super.onStart();
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
// Check if user is signed in (non-null)
firebaseUser = auth.getCurrentUser();
}
The emulator has no bearing on the way Firebase Auth actually works. The problem is almost certainly that you're asking the SDK if the user is signed in before the SDK is certain about that. Instead of calling auth.getCurrentUser() you should use an auth state listener to get a callback when the final authentication state of the user is known. It might not be known immediately at launch, as the user's token might have expired and need to be refreshed at the server. This takes time.
Your app should wait until this auth state listener indicates that the user is actually signed. This means that your listener will actually be the thing to move your UI along to do things like make queries and present data to the user.
I've recently discovered that Firebase Auth saves itself on the device even after my app is uninstalled. I can't figure out how to REMOVE this old Auth info.
I don't want a user to still be signed in after uninstalling and reinstalling the app. If for no other reason than my own testing of what I expect to be "clean installs" on the same device.
I understand there is no easy way to capture an uninstall event, so I want to clear out any potential old Auth info on the first launch.
So I added code (which seems to work fine) to check if this is the first launch:
Boolean firstRun = prefs.getBoolean("firstrun", true);
if (firstRun) {
// delete everything an old user could have left behind
// ==> This is where I need help <==
prefs.edit().putBoolean("firstrun", false).apply();
} else {
// move along, not the first launch
}
I've tried (unsuccessfully):
FirebaseAuth authData = FirebaseAuth.getInstance();
authData.signOut();
These calls also seem to be the advice in this related question for iOS, but I haven't been able to apply its wisdom:
Firebase - Deleting and reinstalling app does not un-authenticate a user
Even after calling signOut() the app keeps logging me in under the old account!
My "logout" button uses FirebaseAuth.getInstance().signOut(); and works. Is there something odd (possessed?) about this "old" Auth instance that is being saved after an uninstall that it just won't die?
Specifically when I uninstall and then install/run from Android Studio:
at first authData and currentUser both are not null
I call the above code, trying to get rid of this old user
3 millisecond later (immediately after I call that
code) they are still NOT NULL.
Another 2 milliseconds, currentUser IS NULL (yay?)
Another 71 milliseconds... still null (so far so good)
Just under a second later... I'M SIGNED IN AS THE OLD USER?! How is this possible?
In the Firebase Console under Authentication, this account is shown as last signed in 6 days ago. So it's not somehow getting re-signed-in.
Does anyone know how to remove FirebaseAuth data from a device? I don't want to "delete" the user account, just remove all traces of it from this device.
Oddly enough, the account I keep getting unwillfully logged in under isn't even the last account that logged into my app on this device. And this was never a problem in the past (hence my not even knowing that Firebase saved Auth after uninstall). So it looks like Auth info isn't always saved after uninstall... but when it happens it's impossible to remove?
Any help much appreciated!
Add android:allowBackup="false" in your <application> in manifest:
From the docs:
android:allowBackup
Whether to allow the application to participate in the backup and restore infrastructure. If this attribute is set to false, no backup or restore of the application will ever be performed, even by a full-system backup that would otherwise cause all application data to be saved via adb. The default value of this attribute is true.
Try also FirebaseAuth.getInstance().getCurrentUser().delete
Firebase stores auth info in shared preference with file names starting with "com.google.firebase.auth.api.". Therefor if you delete these files as part of your log off flow it would help the purpose.
public void clearFirebaseAuthInfo(Context ctx)
{
File dir = new File(ctx.getFilesDir().getParent() + "/shared_prefs/");
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
if(children[i].contains("com.google.firebase.auth.api."))
{
new File(dir, children[i]).delete();
}
}
}
The Firebase Auth doc's recommended way to get the current user is:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
} else {
// No user is signed in
}
So I went ahead and did exactly that at the very beginning of my first activity:
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "⟳ onCreate")
super.onCreate(savedInstanceState)
if (FirebaseAuth.getInstance().currentUser == null) {
Log.d(TAG, "User is null. Sending user to log in.")
val intent = Intent(this, FacebookLoginActivity::class.java)
startActivity(intent)
finish()
} else {
Log.d(TAG, "User has been found. Launching MainActivity")
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
But this is when strange things start happening 😱
Steps:
I killed the app from memory
Deleted all its data & cache
Uninstall & install again then launch
Actual: FirebaseAuth.getInstance().currentUser was NOT null! Okay guessing the Firebase library is trying to do something smart and figure out my previous log in history, but:
The uid it returns is not my user Id. I cannot use this as I already keep data for the user in my DB with an other legit uid previously returned for this user.
I can NOT find this uid on
https://console.firebase.google.com/u/0/project/.../authentication/users How is this possible?
This uid has been popping up at various times causing me errors, and it is always this same rogue uid.
A couple of things I checked:
FirebaseAuth.getInstance().currentUser.providerData
shows that this uid is associated with my Facebook account, so I
must have logged in with it before. (I call FacebookAuthProvider.getCredential(...) in the next activity) But my real legit uid should also be associated with my Facebook account which is the one I am interested in.
FirebaseAuth.getInstance().currentUser.isAnonymous returns false, so
the problem is probably not related anonymous login
How do I clear this "phantom" rogue user id from the system?
How do I check for this? I don't want to call FacebookAuthProvider.getCredential(...) every time the user opens the app.
(Using 'firebase-auth:12.0.1')
If you have a user that is apart of your app and you if you decide to delete its account from the Firebase Console, you need to know that if the same returns to use your app again, another uid is generated, which is obvious that is different from the first one. So this user, even if it has the same details (userName, emailAddress and so on) before it was deleted, is treated as a new user, with a new uid.
I got the same issue as you. I am using flutter with Android device.
This is what I tried:
Clear the cache for the app.
Delete the app.
Restart the phone.
Reinstall the app.
Then, FirebaseAuth.getInstance().getCurrentUser() will no longer hold the value.
For example in my app, I use firestore, it will throw permission error when accessing firestore resource because of invalid userId (it dependes on the security rules). You can make your app defensive to ask user to login again. Or you can do firebaseUser.reload() it will throw userId invalid exception.
The actually reason why FirebaseAuth.getInstance().getCurrentUser() will hold the value before reboot still unknown.