How to manage multiple users in android - android

I am developing an android app which uses firebase authentication. I can login and logout a user at a time. Now my question is I don't want users to logout and enter credentials every time for another user to login. I want to allow users to use their accounts exactly like how Gmail implements it. In Gmail as we know, to view emails from different accounts, we just need to enter the credentials one time and we can just view emails by swiping from left and selecting the account. How can I do that?
I am sorry I am not even able to figure how to ask this question in google. Any link or guidance on how to implement this would be very helpful. Thankyou

Most Firebase products (such as Authentication and the Realtime Database) are tied to a FirebaseApp object for their configuration. This means that if you have multiple FirebaseApp instances, you can get a separate FirebaseAuth from each, and authenticate a different user on each.
FirebaseOptions options = new FirebaseOptions.Builder()
.fromResource(this.getApplicationContext())
.build();
FirebaseApp.initializeApp(this /* Context */, options, "secondary");
FirebaseApp secondary = FirebaseApp.getInstance("secondary");
// Get the auth for this app instance
FirebaseAuth auth = FirebaseAuth.getInstance(secondary);
With this you can have a separate signed in user for each FirebaseApp object.

With FirebaseAuth object you can check if the user has logged or not.
If the currentUser is null in the FirebaseAuth then user has not been logged in yet.
If you want to logout the user then just call firebaseAuth#signout.

Related

Link several user accounts (same email) Firebase

I have the possibility that the user can choose if they want to log in with Google, Facebook, email/password, etc.
After testing my app, the following happened:
I sign up with my name, email, and password
Handle the get started logic
Verify my auth users on Firebase (grey email icon)
Sign out of the account
Now, I want to log in with Google (same email used on the sign-up with email and password)
The Google sign-in worked
Verify my auth users on Firebase (the grey email icon changed into the Google one)
Sign out of the account
Can't log in with email and password anymore but the google sign in worked
After some research, I end up with the Link Multiple Auth Providers to an Account on Android documentation
I realized I have to refactor my code to not use the FirebaseAuth.signInWith methods
This is a little except of my loginEmailAndPassword:
val credential = EmailAuthProvider.getCredential(email, password)
firebaseAuth.currentUser!!.linkWithCredential(credential).addOnCompleteListener{ authTask: Task<AuthResult> ->
if (authTask.isSuccessful) {
I have an 'else' meaning the (authTask.isSuccessful) did not happened and another 'if' with the FirebaseAuthUserCollisionException
val exception: java.lang.Exception? = authTask.exception
if (exception is FirebaseAuthUserCollisionException) {
linkAndMerge(credential)
My goal is to link and merge, and I do not know how to link the accounts (both email grey and Google on Firebase)
private fun linkAndMerge(credential: AuthCredential) {
val authenticatedUserMutableLiveData: MutableLiveData<ResponseState<UserModel>> =
MutableLiveData()
val prevUser = firebaseAuth.currentUser
firebaseAuth.signInWithCredential(credential)
.addOnSuccessListener { result ->
val currentUser = result.user
// Merge prevUser and currentUser accounts and data
// ...
}
.addOnFailureListener {
authenticatedUserMutableLiveData.value = ResponseState.Error("Error")
}
}
My questions:
Can I call something to merge prevUser and currentUser accounts. I just want to the user have the possibility of using different authentications.
I am not worried about the data because if it's the same User UID does not matter if the authentication provider
Can I still use 'createUserWithEmailAndPassword'?
Steps 1 to 9 provide the expected behavior. If you create a user with email and password and right after that you sign in with Google, the account will only be accessible with Google. Why? Because behind the scenes Firebase converts the account that was created with email and password into an account with the Google provider. Unfortunately, you cannot reverse that change.
The link in your question, is referring to the possibility to link an existing account to a specific provider. For example, if you implement anonymous authentication, then you can link that account with Google, for example. This means that the UID remains the same.
If you want to stop that mechanism from happening, then you should consider allowing the creation of different accounts for different providers. You can find this option which is called "Create multiple accounts for each identity provider" right inside the Firebase Console, in the Settings tab inside the Authentication.

How to use multiple accounts in Firebase Auth in Android?

How to use multiple accounts in Firebase Auth in Android? Using a single account works fine. But, when I try logging in with another account, the previous data is gone. How can this be done?
Firebase Authentication has only a single current user per app instance. It does not support having multiple users signed in at the same time, so signing in another users automatically signs out the previous user.
What you can do is create a separate instance of the FirebaseApp and FirebaseAuth variables for each user, and then sign in each user into their own FirebaseAuth instance.
Based on the documentation on configuring multiple projects in your Android ap, that should be something like this:
FirebaseOptions options = new FirebaseOptions.Builder()
.setProjectId("my-firebase-project")
.setApplicationId("1:27992087142:android:ce3b6448250083d1")
.setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
// setDatabaseURL(...)
// setStorageBucket(...)
.build();
FirebaseApp app1 = FirebaseApp.initializeApp(this /* Context */, options);
FirebaseApp app2 = FirebaseApp.initializeApp(this /* Context */, options);
FirebaseAuth auth1 = FirebaseAuth.getInstance(app1);
FirebaseAuth auth2 = FirebaseAuth.getInstance(app2);
We initialize both FirebaseApp instances here with the same configuration data, since you have only a single project. But each instance can then have its own current user.

how to get current active android app user email from firebase using firebaseAuth

My app have two user( buyer and seller).
I am tring to get current user email which is buyers but when i run the below code, it shows previously logged in user email which is the seller's one.
String userID= FirebaseAuth.getInstance().getCurrentUser().getEmail();
How to write firebase code to get current active user email.
Use this code snippet FirebaseAuth.getInstance().signOut(); to sign out the current user properly, after successfully signed out you can repopulate your user model from Firebase Auth/login in new user. Hope your problem will be solved with this.
When you go to the Auth > Sign-In Methods page of your project in the Firebase console. do you have One account per email address on or off? If you allow multiple accounts per email address, you will get null for FirebaseUser.getEmail()

AWS Cognito: how to delete an identity programmatically?

In my Android app, I use AWS Cognito to allow my users to sign up and login. I configured my identity pool so it allows guest users (unauthenticated users) in my app.
So everytime my user logs in or logs out, I call the following code to get an identity ID:
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
this,
"eu-central-1:12345678-1234-5678-9012-1234567890ab",
"eu-central-1");
credentialsProvider.clearCredentials();
credentialsProvider.getIdentityId();
When my user logs in, it creates a new identity the first time, then the user gets the same identity everytime he logs in. But everytime he logs out, a new identity is created, since he's now a "guest" user.
Is that the expected behavior? And if yes, how can I remove an unused identity programmatically (for example when the user logs in, so the "guest" identity is now useless, since a new one will be created when he logs out)?
Thanks for your help.
From the docs, we have:
getIdentityId() Gets the Cognito identity id of the user. The first time when this method is called, a network request will be made to retrieve a new identity id. After that it's saved in SharedPreferences.
clearCredentials() Destroy all the saved AWS credentials but not the identity Id.
so, the behavior you described is totally normal according to the docs.
Now, let's find an approach to deal with the problem.
if you want to continue with your proposition, and delete the identity programmatically after the logout, you can use deleteUser() method from AWSJavaSDK.
However, if you want to keep the same identity for the same user after the logout, you shouldn't clear the cache, cause the won't keep the user any trace of its identity.
I hope this will help.

Signing up a new Firebase account using a currently logged acount(Android)

I'm working on an educational app wherein teachers can create/edit/delete topics and activities for the students while monitoring their progress(like SoloLearn), i'm at 90% progress now and was testing the app when I encountered this problem. I create the app so that only the teacher accounts can create accounts for the students. As I login the teacher account it will show the basic info of the teacher(name, email, advisory class), seems good, but when I created an account for a student(teacher account currentUser), my app replaces the currentUser with the student account that I just created(Tested).
So my question is how can I resolve the issue where in creating a new account within an account replaces the current user?
Basic info of the teachers/students are saved in FirebaseDatabase using email as a key.
I'm using the Firebase Assistant in creating the account.
my Code in retrieving userEmail and DatabaseReference
String currentEmail = mAuth.getCurrentUser().getEmail();
mDataRef = FirebaseDatabase.getInstance().getReference()
.child("AccountInfo").child("Teacher").child(EncodeString(currentEmail));
EncodeString is just a String replace for "." to "DOT".
I think a better and more secure way of doing this is to use the Firebase Admin SDK.
You would set a custom user claim on teachers to differentiate them from students. Then on student creation, send the teacher's ID token and the student's info to a server where you confirm teacher role and then create the user with Admin SDK.
Otherwise, if you just want to create another account without logging out the teacher, you can explicitly [instantiate a new FirebaseApp instance](https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp.html#initializeApp(android.content.Context, com.google.firebase.FirebaseOptions, java.lang.String)) and use the other non-default instance to create the accounts.
However, from a security point of view, the first suggestion is the right way to do it.

Categories

Resources