in the following code:
private val auth: FirebaseAuth
val authResult = auth.signInWithCredential(googleCredential).await()
val isNewUser = authResult.additionalUserInfo?.isNewUser ?: false
What does the isNewUser variable tell us? Does it tell us that the user is new to my app/my app's firestore database? Or, does it tell us whether the user is new to firestore authentication in general? More specifically, can this variable be used to check if the user exists in my app's firestore database?
I found this code snippet in an article that explains how to implement firestore in jetpack compose. My interpretation of the code that the author wrote implies that this value can be used to check if the user is new to my app (in the article, the author calls a method that adds the user to their firestore database if and only if the isNewUser value returns false).
If isNewUser is true, that means the user has logged in to your application ("Firebase Project") for the first time i.e. created a new account with Google or any OAuth provider. This is useful because unlike email password authentication that has separate signInWithEmailAndPassword() and createUserWithEmailAndPassword(), OAuth providers just have signInWithCredential() (or popup/redirect on web).
Firebase Authentication is a different product and has nothing to do with Firestore. They can be used individually.
Related
I'm using firebase in Android Studio with kotlin.
I want to know whether login account is email-register account or google social account.
As I know, if FirebaseAuth.getInstance().currentUser.providerId is "google.com", user used google social login.
And if providerId is "password", user used email register with firebase.
But only I can get "firebase" from providerId.
How can I solve it?
It it is neccessary for making login function.
I can get only "firebase" from providerId.
According to the API documentation, getProviderId() (or just providerId for Kotlin) will always return FirebaseAuthProvider#PROVIDER_ID (which is equal to "firebase").
If you want to determine which authentication channel was used to get this Firebase ID Token, you need to use getProviderData() which contains the UserInfo objects returned from the social logins.
val auth = FirebaseAuth.getInstance();
val hasLinkedGoogleUser = auth.providerData.any{ it.providerId == GoogleAuthProvider.PROVIDER_ID }
I am currently trying to convert an anonymous account into a permanent one using Android Firebase. I am using the email-password provider as a method to create an account. The docs state that you must pass a password parameter into the following code :
val credential = EmailAuthProvider.getCredential(email, password)
My code is the following, I use the FirebaseAuth instance to access the current user which then allows me to access their email however I cannot find a way to access the password:
val credential = EmailAuthProvider.getCredential(mAuth.currentUser.email, password)
Other links I have taken a look at do not improve clarity and cause further confusion.
Firebase Authentication : how to get current user's Password?
How to create "credential" object needed by Firebase web user.reauthenticateWithCredential() method?
Firebase get current user password
Additionally, the last link states that for security reasons we cannot get the password.
I am currently trying to convert an anonymous account into a permanent one using Android Firebase. I am using the email-password provider as a method to create an account.
From this sentence, I understand that you already have anonymous accounts in your project and you try to convert them into permanent users using user and password.
The docs state that you must pass a password parameter into the following code:
val credential = EmailAuthProvider.getCredential(email, password)
That is a normal requirement. Since your anonymous users can join your app without any credentials, in order to be able to convert them, you need to ask each user for an email and a password. That can be simply done in Android, using two EditText objects.
Once you got the user input, you can call getCredential() and pass those values as arguments. Once did that, you can call:
auth.currentUser!!.linkWithCredential(credential)
.addOnCompleteListener(this) { /* ... */ }
Please note that auth.currentUser represents the anonymous users. When you call linkWithCredential() and you pass the credential object as an argument, you're actually converting the anonymous user into a permanent user.
Since the current account is anonymous, it doesn't have an email and password yet.
The common flow is that you first sign in the user anonymously, without asking them for any information. Then later (when the user is ready to sign in explicitly) you ask them for their email and password, use those to create email credentials, and then link them to the anonymous account.
In firebase you can access the current user's data by using FirebaseAuth.getInstance().getCurrentUser()..., I am wondering is there a way to access other Authenticated users public data by their id or email.
Accesing user data is a dangerous operation, imagine an app that allows you to change others people user name.
So in the clients you cant, unless you duplicate the user data to the RTD or the Firestore and using rules set privacy controls.
What I think you are looking for is something like the admin sdk for auth that allows to search for users using email or uid.
You can see the docs here
https://firebase.google.com/docs/auth/admin/manage-users
If you dont want to setup a server you can go all the way in the Firebase way; using Functions. Functions is a trusted enviroment like a server, so it can use the admin sdk for auth. You could create an onCall function for doing whatever you want.
If you want to only search users, please consider having a searchable version of the user data on any database, if you are looking for an admin type of feature then Functions onCall is what you need.
You will probably want to set admin privileges using customs claims
https://firebase.google.com/docs/auth/admin/manage-users
exports.userCreationListener = functions.auth.user().onCreate(user => {
const admins = {
"first#admin.com": true
};
const email = user.email;
if (!admins[email]) {
return false;
}
const uid = user.uid;
return admin.auth().setCustomUserClaims(uid, {superAdmin: true}).then(
()=>admin.database().ref(`users/${uid}`).set(true)).catch(error=>{
console.log("SUPER_ADMIN_UPDATE_ERROR", error);
return false;
});
});
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
}
Read guide https://firebase.google.com/docs/database/admin/retrieve-data
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.
I am making an android chat application using firebase. So far I have made a common group chat app. Now I want to make it an individual chat app, which will have a Users list and when we select a person from that list we can chat individually with him/her. However I am not able to get this Users list from Firebase. I have kept Google Sign in and Email sign in options in the Firebase Auth UI. Any help would be appreciated
If you need to lookup users by uid, email or phoneNumber, you can use the Admin SDK to do so:
https://firebase.google.com/docs/auth/admin/manage-users
You also even have the ability to download all your users:
https://firebase.google.com/docs/auth/admin/manage-users#list_all_users
You would need to do that from a Node.js backend server or via HTTP endpoints with Firebase Functions.
In addition the Admin SDK allows you to set custom user attributes which could be helpful if you want to create different user groups:
https://firebase.google.com/docs/auth/admin/custom-claims
admin.auth().setCustomUserClaims(uid, {groupId: '1234'})
The Firebase Admin SDK allows retrieving the entire list of users in batches:
function listAllUsers(nextPageToken) {
// List batch of users, 1000 at a time.
admin.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log('user', userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch(function(error) {
console.log('Error listing users:', error);
});
}
// Start listing users from the beginning, 1000 at a time.
listAllUsers();
Note: This API is currently only available for the Admin Node.js SDK.
via https://firebase.google.com/docs/auth/admin/manage-users
As pointed out by #Sam earlier, you can fetch details from Firebase DB. So every time a user signs up, add his FirebaseUser details (preferably his UID, under which you store his other details if required) to the DB. Then simply put a listener on the Database in your next activity, and you can fetch a list of all registered users.
const allUsers: firebase.auth.UserRecord[] = [];
const listAllUsers = async (nextPageToken?: string) => {
const res = await firebase.auth().listUsers(1000, nextPageToken);
allUsers.push(...res.users);
if (res.pageToken) {
await listAllUsers(res.pageToken);
}
};
await listAllUsers();
console.log(allUsers)
You cannot retrieve the data of all authenticated user from Firebase Authentication, however you can only get the current user.
In Order to get the data of registered user you need to store it into database and then retrieve the whole array, or you can just keep the authentication flag which can be set or reset if the user is registered in your all-user table and vice versa.
As mentioned by #Jason you can try Admin SDK as it is mentioned in the documentation that listAllUsers() can retrieve batch of user data.
The detailed explanation can be found IN THIS THREAD.
If you want to view a list of users that has registered thru Firebase Auth, you may view them in https://console.firebase.google.com/ then go to your project and select authentication, in the Users list is all the users that have registered thru Firebase Auth.