Android Firebase how to save and retrieve data under specific user - android

i am trying to integrate my app with firebase to save simple data on cloud.
Example:
user open the app and login.
user write some stuff,the data saved on cloud.
when the user will use the app again he will see his data.
i have read the docs but i coud not find any example how the
structure works between the user and the data.
user logged in , now how to save strings/object for that user?
what i tried:
user login or authenticate the user
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
// user is logged in
} else {
// user is not logged in
}
}
});
now how to save under that user objects/strings?

It looks like you're using and old Android API for Firebase.
With the latest Android API there is no more need for "https://<YOUR-FIREBASE-APP>.firebaseio.com" in your code.
I would suggest to migrate, using that migration guide.
Once you have logged your user following that guide
Then you can store user information like in that documentation :
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase.child("users").child(userId).child("name").setValue("John");
Don't forget to change your security rule in Firebase to make sure only this user can access his own data: guide here. It's very easy and quick to do and very important for keeping your user's data private.

Related

Firebase Authentication using email and google

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 }

How to get a Firebase user by its id?

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

Retrieving a list of users who have registered using Firebase Auth

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.

Given a simple e-mail/password authentication scheme in Firebase, what is the most appropriate method of expedited login?

I'm writing an android app that requires login for access to our Firebase details. I'm currently using the "e-mail & password" authentication method. What I would like to implement is some fast login procedure once the user has logged into the app at least once. If I didn't care at all about security or best practices, the way to do this would be to squirrel away the user's credentials in some file local to the device. But I do.
Some googling suggests using OAUTH, but if I understand correctly, that would require a user to have an account with a supporting service (Google, Facebook, Twitter, Github). That association doesn't feel appropriate for this app's branding. An independent e-mail password fits better.
So what would you all suggest for an implementation of fast login machinery?
Edit: forgot to mention, if the suggested methods have a specifiable expiration, thats a plus.
You can use shared preference.
When user login first time save uId in shared preference and check every time when user come to your app that uId is exist or not if exist no need to do login.
And when user logout from application clear all shared preference.
Firebase Authentication automatically keeps the user signed in across app restarts. If you attach an onAuthStateChanged listener when the app restarts, the user can continue working without having to sign in again.
See this example from the documentation for getting the currently signed-in user:
The recommended way to get the current user is by setting a listener on the FirebaseAuth object:
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
});

How do you keep the user logged in across multiple sessions on Firebase on Android? [duplicate]

This question already has answers here:
How deal with cold start of an app where user has beeing logged with Firebase at previous run
(4 answers)
Closed 6 years ago.
I'm currently using Firebase's email and password authentication to login my users.
How do I keep a user logged in across multiple sessions so that if they close the app and come back later, they don't have to login again?
Do I need to save an auth token in my SharedPreferences and attempted to login the user via this token when they start the app again? If so, is this the token in the AuthData object returned by authWithPass() (via Firebase's API), and which Firebase login method should I use with this token?
Firebase already saves the authentication token in the SharedPreferences of your app and restores them when the app restarts.
If you are not seeing this as "the user is already authenticated" behavior in your app, it is likely that you're not monitoring authentcation, but only handle the active flow to log users in.
From the Firebase guide for Android developers (which I highly recommend you read) comes this example:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
// user is logged in
} else {
// user is not logged in
}
}
});
Also see:
How deal with cold start of an app where user has beeing logged with Firebase at previous run
How to keep a user persistent logged in through my Android application with Firebase

Categories

Resources