Reputation: 189
I've built a website where users can log in through Facebook, Google, or Twitter, and then their email, name, and profile picture URL will be saved to a Firebase database. Now, I'm trying to obtain the currently logged in user's profile picture URL from the Firebase database, but I have no idea where to start. I've read Firebase's accessing data documentation, but didn't understand it enough to make it work.
This is the function that checks if the user is logged in and then checks if they're an admin. I need to grab the currently logged in user's profile image on the line labeled "RIGHT HERE".
$(document).ready(function() {
var ref = new Firebase("https://mpacares.firebaseio.com/");
ref.onAuth(function (auth) {
if (auth) {
var userRef = ref.child('users').child(auth.uid);
userRef.on('value', function (snap) {
var user = snap.val();
if (user) {
// RIGHT HERE: set the user image src to user.picture
} else {
// TODO: hide the user image
}
}, function (error) {
console.log(error);
});
var adminRef = ref.child('admins').child(auth.uid);
adminRef.on('value', function (snap) {
var user = snap.val();
if (user) {
console.log("You're an admin!");
// enable admin button
} else {
console.log("Sorry, no access for you.");
// disable admin button
}
}, function (error) {
console.log(error);
});
} else {
// logged out
}
});
});
Additionally, you can view my current Firebase app on https://mpacares.firebaseapp.com/.
Upvotes: 3
Views: 5745
Reputation: 189
Here's what worked for me in the end:
$(document).ready(function() {
var ref = new Firebase("https://mpacares.firebaseio.com/");
ref.onAuth(function (auth) {
if (auth) {
var userRef = ref.child('users').child(auth.uid);
userRef.on('value', function (snap) {
var user = snap.val();
if (user) {
$(document).ready(function() {
var ref = new Firebase("https://mpacares.firebaseio.com/");
var user = ref.getAuth();
console.log(user);
var userRef = ref.child('users').child(user.uid);
userRef.once("value", function(snap) {
var user = snap.val();
console.log(user);
console.log(user.name);
console.log(user.picture);
console.log(user.email);
var userName = user.name;
var userPicURL = user.picture;
var userEmail = user.email;
document.getElementById("account-txt").innerHTML = user.name;
$(".account-img").attr("src", userPicURL);
});
});
} else {
$(".account-txt").hide();
$(".account-img").hide();
}
}, function (error) {
console.log(error);
});
Upvotes: 2