If I use the user registration and login through the firebase authentication, the user information are stored in the firebase database side. How can I get the user information (such as FirstName, LastName, Gender and etc.) and store in my own database? Is it use the access token to call my API to check the user identity?
I suggest to use a cloud functions to triggers when user was created.
exports.userCreate = functions.auth.user().onCreate((user) => {
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
// Write insert email, displayName, ... to your own database.
});
Ref: https://firebase.google.com/docs/functions/auth-events
When a user registers for your app using Firebase Authentication, no information is sent to your Firebase database by default...they only have an Auth account.
You need to manually collect and send information to your database. Once a user is authenticated within your app, you can listen for their Auth user info with onAuthStateChanged.
Lotsa folks then use the uid as the key in their database and store profile info below that.
Related
We are creating user profile in firestore using cloud function
when new user create cloud function will trigger and we write the user info to firebase collection but, now in my firebase we have 2 apps and in need to store user profile in two different collection The issue is how can i identify which app is users by the user for login app A or app B
Is there any way to do that?
You need to send to the cloud function the tokenId of your user, you can get the tokenID doing something like this:
firebase.auth().currentUser.getIdToken(true).then(function (token) {
// Send the token
})
Then, on the cloud function you need to decode the tokenID to get the current userId, you can do something like the following:
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var uid = decodedToken.uid;
})
With the uid, you can use admin.auth().getUser(uid) to get the current user record.
I'm creating an application with flutter and using firebase for authentication in data storage (possible more).
I have an auth onCreate cloud function which adds some user information to my realtime database whenever a user is created. But, I also want to set a displayName and photoURL when the user is created because if I update the profile info after, the onCreate won't be triggered. I also don't want users to be able to write to this part of the database.
Is there any method I can user to pass an displayName and photoURL when the user is created? Currently, I'm just creating the user with an email and password.
Thanks.
Instead of creating the users directly from the client, you can use a callable function to create users using the Admin SDK, which includes displayName and photoURL in its options.
Let's say I've a user id
String uid = "1234abcdefgh890";
Now, I'd want to get a FirebaseUser using this uid, how do I do that?
FirebaseAuth auth = FirebaseAuth.instance;
FirebaseUser user = (await auth.signInWithXXX(uid)).user; // is there any method like this
How can I get the FirebaseUser then?
There is no API in the Firebase client-side SDKs to get user information based on a UID, as this could potentially be a security concern.
If you need this information, you can either implement your own server that uses the Firebase Admin SDKs (which do have this functionality), or you can store user information in a secondary database, such as Firebase's own Realtime Database or Cloud Firestore. Then you can query this database from the rest of your application, and secure access to fit your needs with the database's server-side security rules.
Also see:
How do I return a list of users if I use the Firebase simple username & password authentication
Firebase get user by ID
How to get the user email in Firebase based on user id
Using Firebase User UID to retrieve profile info
Firebase get Authentication details using UID
I am managing SQL server database along with Firebase. I have created user's account in Firebase from back-end by below method and stores other properties
in Firebase by providing User UID as unique key.
firebase.auth().createUserWithEmailAndPassword(Email, Password).then(function (user) {
firebase.database().ref("Users/" + user.uid + "/").set({
favouriteId: FavouriteId,
hotelId: HotelRef,
isActive: IsActive,
isLoggedIn: IsLoggedIn,
name: Name,
vendorId: VendorId
}) });
User can use above credentials to login into mobile app.To change password of user I am using reset password by email from Firebase. Here Password is changing from mobile side and I am unable to update that password in SQL server.I want to update new password in SQL server database.
I have searched for above but I didn't find any solution or other way to get password from Firebase.
Currently I am calling API from mobile side to update password in SQL server.
Is there any way to retrieve updated password from Firebase database?
Why are you storing the password (never a good idea to store plain text password) when Firebase Auth already does this for you securely using best practices including salting and hashing the password. If you plan to use Firebase Auth, you may as well let them manage password authentication for you. If you need to migrate to another auth system at some point in time, Firebase Auth provides multiple tools to get the hashed passwords via CLI SDK and Firebase Admin SDK.
I am building a server route that I wish to restrict for use only by authenticated users. I plan to send a user.uid with a POST to this route, and I want to validate the UID is one that exists in Firebase. I know I can add UIDs manually in Firebase and check against this data, but is it possible to see what UIDs Firebase authentication is tracking? I think this approach would be better then checking against my own list.
The purpose for this is to ensure that these routes are not accessed with a phony UID (e.g. for malicious purposes).
Validating a UID is not enough to block malicious users: 1) the attackers could pretend to be other users by sending other user's UID, and 2) UID never changes or expires, which means there is no way to enforce the users (or attackers) to re-authenticate.
What you need is to pass the Firebase token from client app to your server, and validate the token before accepting it.
The token is securely signed by Firebase private key. No other party can issue a valid Firebase token.
The token is valid for only one hour. Firebase server will check the account status (e.g. password change event) before issuing a new token.
The token payload contains UID and audience. You should verify audience is your own application.
You can use Firebase Admin SDK or third party libraries to verify a Firebase token. See Firebase doc for details.
You can check whether a specific UID corresponds to a Firebase Authentication user in your project by using the Firebase Admin SDK on your server. From the Firebase documentation on retrieving user data:
admin.auth().getUser(uid)
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully fetched user data:", userRecord.toJSON());
})
.catch(function(error) {
console.log("Error fetching user data:", error);
});
A UID is part of the payload when a Firebase user is authenticated to Firebase and is null when a user is not authenticated. You can get the UID upon user authentication. The syntax is different depending on what framework you are working in.
Check out the Firebase API Reference for specific syntax and examples: https://firebase.google.com/docs/reference/
create a token in your client app
private String getAuthTokenAndPost(){
mAuth.getCurrentUser().getIdToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
#Override
public void onComplete(#NonNull Task<GetTokenResult> task) {
if(task.isSuccessful()){
String idToken = task.getResult().getToken();
sendReqToServer(idToken);
}else{
Toast.makeText(CartActivity.this, "couldn't generate Token", Toast.LENGTH_SHORT).show();
}
}
});
return "";
}
then use firebase admin SDK on your server side, here is an example of a Node server
getAuth()
.verifyIdToken(idToken)
.then((decodedToken) => {
const uid = decodedToken.uid;
// ...
})
.catch((error) => {
// Handle error
});
ID token verification requires a project ID. The Firebase Admin SDK attempts to obtain a project ID via one of the following methods:
If the SDK was initialized with an explicit projectId app option, the SDK uses the value of that option.
If the SDK was initialized with service account credentials, the SDK uses the project_id field of the service account JSON object.
If the GOOGLE_CLOUD_PROJECT environment variable is set, the SDK uses its value as the project ID. This environment variable is available for code running on Google infrastructure such as App Engine and Compute Engine.
check the document