Firebase Realtime Database Connection Data - Web - javascript

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..

Related

Getting Uncaught TypeError in Firebase Auth get current user email

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
// ...
}
});

Firebase Auth Login not showing logged in user name

I'm using firebase web authentication to log users into my website which works perfectly fine - but I want to be able to show the name of the user logged in. How do I do that?
When a user signs up, it will be written with some basic fields (email, uniqueID, etc) to the Firebase Authentication DB (which you have access to, but you don't have full control of, since it's controlled by the Firebase Auth system).
Once your brand new user is created, you'll get a UserCredential object with basic information of your user. Use the uniqueID field (UserCredential.user.uid) to write your user details with as many fields as you want (username, email, fullName, address, preferences, etc) to your Firebase database (realtime DB or cloud Firestore). I think it's a good practice to store under a document with the uniqueID created by the Auth system.
Once you've done that, and that users logins in at a later time, you'll get another userCredential object that contains the uniqueID for that user.
You'll use that uniqueID to access your database where you stored your users details and you will be able to retrieve all the data that you want.
See the code below (I'm using React): uppon a successful signUp, we get a UserCredential object, which we can use to read the uniqueId uid that it was just created, and use that to create a document in our database with that same id. We can add as many fields as we want. In this case, I added username (which I'm getting from my signup form) and email (which I'm getting directly from the UserCredential object).
UserCredential docs
Create User with Password and Email docs
handleSubmit(event){
event.preventDefault();
const { email, passwordOne} = this.state;
// SIGN UP FUNCTION
this.props.firebase.auth.createUserWithEmailAndPassword(email, passwordOne)
// SAVING USER DETAILS TO MY DATABASE
.then((UserCredential) => {
const username = this.state.username;
this.props.firebase.db.collection('users').doc(UserCredential.user.uid)
.set({
username: username,
email: UserCredential.user.email
})
.then( () => {
this.setState({ ...INITIAL_STATE });
this.props.history.push('/');
}
)
.catch(error => {
this.setState({ error });
}
);
}
)
.catch(error => {
this.setState({ error });
}
);
}

Automating Firebase and Javascript (VueJS)

I'm adding users manually as I don't want them to access the app without authorisation.
Upon adding a user,I would like to add a new child to the database (named from the user email) and send him an email with his logins.
So far I've arrived to this, that doesn't work (webpack) and I cannot create a child using the current user's email:
firebase.auth.user().onCreate(function(event) {
var uid = event.data.uid;
return admin.database().ref("/users/" + uid)
});
I also found this one for the email:
exports.sendWelcomeEmail = functions.auth.user().onCreate(function(event) {
var uid = event.data.uid;
return sendEmail(uid);
});
Do you have any idea what the formula looks like to create a child in the DB with the user and send him an email with his credentials right upon creation of a new user.

Firebase React Native Current User confusion

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

Check for new user

I want to know when a user logs in via a provider(twitter,facebook,etc...) If he is a new user. If so then add his data to my firebase.. Currently i have read this:
https://www.firebase.com/docs/web/guide/user-auth.html
And it tells me to do:
var isNewUser = true;
Then check by saying
if(authData && isNewUser){
//This is a new user
}
But it dosent work... I logged in with the same account but it tells me its a new user...
Generally with Firebase, you would have a /users node where you would store other data about your users
users
user_id_0
name: "Buck Murdock"
email: "buck#moonbasealphabeta"
user_id_1
name: "Ted Striker"
email: "ted#airplane.com"
The user_id is the Firebase assigned user id.
When a user starts to access your App, you would query your /users node to see if, for example, their email already exists. If not, then you create the user and add them to the /users node.
Oh - and refer to the section Storing User Data in the Firebase guide as you may have overlooked the comment
// here we will just simulate this with an isNewUser boolean

Categories