I am attempting to make a "Welcome, {username}" page after the user logs in to my app. I am getting an undefined error when trying to pull the current user info into my view, and am only able to load user data in a componentWillMount wrapper.
What's the best way to get the user data to display after the component "mounts?" Perhaps I am not fully understanding this concept?
var user = firebase.auth().currentUser;
var name, email, photoUrl, uid, emailVerified;
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
emailVerified = user.emailVerified;
uid = user.uid; // 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 User.getToken() instead.
}
You can get user after login by this code if You use firebase JavaScript
Related
I am trying to get the email of the currently signed in user in my Firebase app, but it keeps giving me an error.
This is my code for getting the current user email:
user_email = firebase.auth().currentUser.email
The error that I get is:
Error Image
It looks like firebase.auth().currentUser is null at the time when your firebase.auth().currentUser.email runs. This is quite common, as Firebase refreshes the user's authentication state when the page loads, and this requires it to make an asynchronous call to the server.
For this reason, you should not assume there is a user signed in. You should either put a check around your current code:
if (firebase.auth().currentUser) {
user_email = firebase.auth().currentUser.email
}
Or (and often better) you should use a so-called auth state listener, to have your code automatically respond to changes in the user's authentication state. From the Firebase documentation on getting the currently signed-in user, that'd be:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
user_email = firebase.auth().currentUser.email;
// TODO: execute code that needs `user_email`
} else {
// User is signed out
// ...
}
});
When a user is authenticated I trigger a cloud Firestore Cloud Function below;
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase)
exports.createUserAccount = functions.auth.user().onCreate((user) => {
const uid = user.uid
const firstName = user.firstName
const familyName = user.familyName
const displayName = user.displayName
const email = user.email
const photoURL = user.photoURL
const newUser = admin.firestore().doc(`/users/${uid}`)
return newUser.set({
firstName: firstName,
familyName: familyName,
displayName: displayName,
email: email,
photoURL: photoURL,
})
})
I run into an issue when a user is logged in anonymously. I have tried adding a const isAnonymous = user.isAnonymous and then returning it under;
return newUser.set({
isAnonymous: isAnonymous,
ERROR LOG IN CONSOLE
Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field isAnonymous).
My question is how do I check if the user is anonymously logged in or not through a Firebase Cloud Function?
The UserRecord object delivered to your auth function will never have an isAnonymous property on it. That's why it's always taking the value undefined. Check the link to the API documentation to see what's there. I'm not sure how you came to the conclusion that it should be there.
Each authentication provider that has verified an account is present in the providerData array property of the UserRecord object. You should look through that array to check if it's an anonymous account. Specifically, you should be checking the providerId field of each UserInfo object in the providerData array. I'm not 100% certain if this is the correct approach, but from what I'm observing, an anonymous account will have an empty providerData array, since it's not been verified by any auth providers.
As long as you are using email-based authentication (email+pass & OAuth) then you can simply check
if (user.email !== null){
// Run this code if the user is not anonymous
}
Docs
As far as I know there is no direct API for checking if a user is anonymous using the firebase admin sdk. By checking that a user has been active and don't have any connected login providers I believe it should work however.
const user = await admin.auth().getUser('Bp7DmEl5HKcDKrQr7QFVnQXS8FH1')
const hasBeenActive = user.metadata.lastSignInTime != null
const hasProviders = user.providerData.length > 0
const isAnonymous = hasBeenActive && !hasProviders
Note that the reason for the active check is to filter out users who are created manually using either the firebase console or with the admin sdk. Depending on your use case you might want to consider them anonymous as well.
I have to show data belonging to a user that logged in.
My database structure is as follows:
Users/Drivers/Uid/name,phone...
How can I show the data of a user that logged in by using JavaScript as a Text?
<a> Username </a>
If you have this HTML:
<a id="username"> Username </a>
And this database structure:
Users
Drivers
Uid: { name: "Name", phone: "Phone number" }
Then you can display the name of the current user with:
var currentUser = firebase.auth().currentUser;
var userRef = firebase.database().ref("Users/Drivers").child(currentUser.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
So this code does (line by line):
Determine the current user
Create a reference to that user's data in the database
Starts listening for that data, meaning it loads the current data, and then monitors for any changes
Puts the name of the user into the element.
Line 4 will be called immediately, with the current value of the user, and then every time that user data change.
Also see the Firebase documentation on listening for values.
If the page can also be loaded when the user is not signed in (yet), you'll want to make sure to only run this code when the user did sign in. You can do this by using a so-called auth state change listener, which is called whenever the user's auth state changes:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var userRef = firebase.database().ref("Users/Drivers").child(user.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
}
});
See the Firebase documentation on getting the current signed in user..
const promise = firebase.auth().signInAnonymously();
This is the code i use to create anonymous authentication.
I get the name of the visitor and i have to store
const user_id = response.uid;
const userPromise = firebase.database().ref('users/' + user_id).set({
username: this.state.name
});
response.uid is received from promise.
Again, when the user visits the site again
firebase.auth().onAuthStateChanged(user => {
I have to grab uid first, i need to use the firebase api to fetch the username.
Is it possible to store username in identifier column?
A good place to store the user name is in the display name field of the Firebase Authentication profile. You can read this with firebase.auth().currentUser.displayName and set it through updateProfile.
Im currently working on a side project with firebase on web and it uses user auth. I have the user logging in and then creating a game room which redirects to a separate page for the game "room". After the page redirects though i cannot pull any of the users data and the only way that im doing it is by re initializing firebase and using
auth.onAuthStateChanged(function(user) {
if (user && user != null) {
uid = user.uid;
email = user.email;
currUser = user;
} else {
//user isnt logged in
window.location.href = 'index.html';
}
There seems to probably be an easier way to do this but i cant seem to get it working and this way also messes up sections of my other code.
Attaching an onAuthStateChanged callback is the idiomatic way to get the user.
You can also get the user with firebase.auth().currentUser. But if a token refresh is required, you may in that case mis-detect that there is no user. That why an onAuthStateChanged callback is recommended.
See the Firebase documentation on getting the current user.