its given undefined. cant retrieve name from firebase - javascript

i want to get user data from firebase after login. when I get the name from database it is providing value as undefined.. why?
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.userName;
var user = user;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
}

Remember that firebase auth saves only the following data:
email: 'user#example.com',
emailVerified: false,
phoneNumber: '+11234567890',
password: 'secretPassword',
displayName: 'John Doe',
photoURL: 'http://www.example.com/12345678/photo.png',
disabled: false
So user.userName doesn't exist.
You can use displayName to save the username but if you really use it to save the name you can create a node called users in firebase realtime database where you could save the username based on UID, something like this:
users
->akdjf231dkeimdla
->username: jamesbond007
After you code could be:
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.displayName;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
//Here are reading the username from the database
var username = snapshot.val().username;
});
}
If you use firebase realtime database remember to add the firebase realtime database library.
For more information: https://firebase.google.com/docs/auth/admin/manage-users

Related

Firebase keep user logged in when navigating to other pages

I'm currently able to log in to my user account and successfully navigate to my dashboard while still logged in, but when I go to any other page, my login status is gone. Another issue is when updating my user's info, how can I write the function so that it's updating the info based on who's logged in? I have provided my code below. Thanks!
Edit profile JS:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth()
auth.onAuthStateChanged( auth,user => {
var user = firebase.auth().currentUser;
if (user) {
alert("User active: ");
// User is signed in.
var email = user.email;
var uid = user.uid;
//Take user to a different or home page
window.location.href ="editprofile.html?id=" + uid;
} else {
alert("No active user please signup or sign in.");
window.location.href ="login.html?error";
}
});
var studioName, email, password, firstName, lastName, address, country, state, city, zip, phoneNumber;
function updateStu() {
//Get data
studioName = document.getElementById("studioName").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
address = document.getElementById("address").value;
country = document.getElementById("country").value;
state = document.getElementById("state").value;
city = document.getElementById("city").value;
zip = document.getElementById("zip").value;
phoneNumber = document.getElementById("phoneNumber").value;
console.log(studioName, firstName, email);
firebase
.database()
.ref("/studiopick/studio/users" + studioName)
.update({
//studioName : studioName,
firstName : firstName,
lastName : lastName,
email : email,
password : password,
address : address,
country : country,
state : state,
city : city,
zip : zip,
phoneNumber : phoneNumber
});
document.getElementById("studioName").value ="";
document.getElementById("email").value ="";
document.getElementById("password").value ="";
document.getElementById("firstName").value ="";
document.getElementById("lastName").value ="";
document.getElementById("address").value ="";
document.getElementById("country").value ="";
document.getElementById("state").value ="";
document.getElementById("city").value ="";
document.getElementById("zip").value ="";
document.getElementById("phoneNumber").value ="";
alert("Data Updated");
};
For your first question:
You are using the auth.currentUser property instead of the user returned from onAuthStateChanged
As per The Docs:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
If user is returned successfully from onAuthStateChanged you can set the value of the returned user globally to access it throughout the app. Otherwise you can navigate to /login (or equivalent).
For your second question:
This depends on how you structured your database. It’s common practice to use the Firebase Auth Id as the users/ which can then be referenced from user.uid.
If you would like to keep record of who created or last edited a document you can keep fields that contain the users id.
Firestore also has security rules which leverage custom claims to secure the database CRUD operation.

Using localstorage to store login info

I have been working on a project where we can store login info so that once a user registers, the data gets saved in the localStorage object. I have mentioned some javascript code to show that:
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
function register() {
localStorage.setItem("username", user.value);
localStorage.setItem("password", pass.value);
localStorage.setItem("email", email.value);
document.getElementById("id01").innerHTML = "Registration successful";
}
function login() {
var checkuser = localStorage.getItem("username");
var checkpass = localStorage.getItem("password");
if (checkuser === user2.value && checkpass === pass2.value) {
document.getElementById("demo").innerHTML = "You are now logged in.";
} else {
document.getElementById("demo").innerHTML = "Incorrect username and password";
}
}
In the javascript code mentioned above, i have used the localStorage object to store the values. I have stored the username in a user property, the password in a pass property and the email in an email property.
My question is: Is there any way where we can store the username, password and the email in one property(user property)?
Yes, you can do this by putting all the features you want in one object.
Example here
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
var user = {
email:email,
pass:pass,
//.. other properties
}
then you can set like this
localStorage.setItam("USEROBJ",JSON.stringify(user));
When you want to call this you should use like
var user = JSON.parse(localStorage.getItam("USEROBJ"));
By the way you can read this
Storing Objects in HTML5 localStorage more detail about you question
You can store JSON as a string in localStorage property and then parse it
function setUser() {
localStorage.setItem('user', JSON.stringify(user));
}
function getUser() {
user = JSON.parse(localStorage.getItem('user'))
}

Listening query with data filtering

I have this structure
comments:
- FG1MaPfTFsdgdsgsruL9Cgx5sY2
+ content
+ value: "My comment"
+ creator: "0U1MaPfTF2fwcgqWuruL9Cgx5sY2"
+ date_create: "2015-02-21T12:40:35Z"
+ users[]
+ CByXgSgB4khZ5LgugXGRdfK7CLk2
+ XakJ8zn711bUeSpCK1ss7Fsz7JX2
+ relations[]
+ HTyXgSgB4khZ5LgugXGRdfK7CLk2
+ CakJ8zn711bUeSpCK1ss7Fsz7JX2
+ settings[]
+ duration: 2
How to write the appropriate query listening in the application so that when the user UID appears in users[] it will immediately receive a message.
An additional filter will be time in duration
First get the user uid:
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
let database = firebase.database();
let userRef = database.ref("users").orderByKey().equalTo(uid);
userRef.on('value', ((snapshot) => {
if(snapshot.exists()){
console.log(snapshot.val());
}
});
}
Try the above, first retrieve the uid then add a reference to node users and using orderByKey() you can query on the uid, and then using exists() you can check if it exists in the database or not.

Unable to add in new user to Firebase after the alert box?

I am trying to create a register user page and saving it into Firebase.
My form includes first name, last name, email, password and confirm password.
I am able to create a new object into my Firebase Database, but when I added the if else statement to make sure the password and confirm password matches, it keeps on giving me:
"Uncaught Error: Firebase.push failed: first argument contains undefined in property 'projectdatabase.password' error."
after the alert box.
It works fine if password and confirm password matches. How can I solve this error?
if(firebase.apps.length===0){
firebase.initializeApp(config);
var sFName = document.getElementById("sfname").value;
var sLName = document.getElementById("slname").value;
var sEmail = document.getElementById("semail").value;
if((document.getElementById("spassword").value)==(document.getElementById("sconfirmpassword").value)){
var sPassword = document.getElementById("spassword").value;
var dbRef = firebase.database().ref().child('projectdatabase');
//store the data in Javascript object
var postData = {
firstname : sFName,
lastname : sLName,
email : sEmail,
password : sPassword
};
dbRef.push(postData);
document.getElementById("response").innerHTML =
"Registered!"
} else{
alert("Re-Enter confirm password!")
var sFName = document.getElementById("sfname").value;
var sLName = document.getElementById("slname").value;
var sEmail = document.getElementById("semail").value;
if((document.getElementById("spassword").value)==(document.getElementById("sconfirmpassword").value)){
var sPassword = document.getElementById("spassword").value;
var dbRef = firebase.database().ref().child('projectdatabase');
var postData = {
firstname : sFName,
lastname : sLName,
email : sEmail,
password : sPassword
};
dbRef.push(postData);
document.getElementById("response").innerHTML =
"Registered!"
}
}
}

No result displaying firebase datas

I am a beginner in Javascript and Ionic, and I try to get my head around simply displaying datas from the database.
However I can't check my console while doing this for various reasons of device.
Anyway, here is the code I use to display the "description" of a user :
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
var description = descriptionSnapshot.val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
All I want is that when I write {{description}} on a html page linked to the controller that has that code, it displays the data of database for the user "-KOkwpzslw9NyUrTtvA7" at "displayDescription" (the name of one of the field in that user's database)
However it doesn't display the data. The page shows up, no particular error showing up, but the data just doesn't show up.
Here is how I made my controller (full view) :
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.provider;
description = user.displayDescription
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
profileEmail = email;
//Set provider.
provider = provider;
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
var description = descriptionSnapshot.val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
});
Any idea to help a NOOB ? :p
EDIT : Add the JSON of my database :
{
"-KOjv0LDdoWrc3uApvPi" : {
"dateCreated" : "Tue Aug 09 2016 11:29:18 GMT-0400 (EDT)",
"email" : "bla#blabla.net",
"provider" : "Facebook",
"userId" : "FMXlUQZth5aehQLT2TKZZJZdJBh2"
},
"-KOkwpzslw9NyUrTtvA7" : {
"dateCreated" : "Tue Aug 09 2016 16:16:52 GMT-0400 (EDT)",
"displayDescription" : "no description",
"email" : "blibli#blibli.com",
"provider" : "Facebook",
"userId" : "F9Z7YhSlmAQqOH5FVjBSV2CkYZG3"
}
}
EDIT 2 :
I considered going for another solution, it still doesn't want to work !
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider, description;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.provider;
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
$scope.profileEmail = email;
//Set provider.
$scope.provider = provider;
var descriptionRef = firebase.database().ref('accounts/' + user + '/displayDescription/' );
descriptionRef.on('value', function(snapshot) {
description = snapshot.val();
$scope.description = description;
$scope.$apply();
});
});
To answer the main problem here, you're not exposing 'description' in the $scope, so the HTML template doesn't know that 'description' exists. So by calling {{description}}, you're probably getting an undefined, and that's why it isn't printing anything.
Then, referring to firebase. The statement firebase.auth().currentUser returns a firebase.User or null depending on whether you're logged in or not. A firebase.User does not contain a definition for provider. Instead, try using providerId or providerData. Also, a firebase.User neither contains a definition for displayDescription. That's an arbitrary key you defined in the user data as for /accounts/-KOkwpzslw9NyUrTtvA7/displayDescription.
If I'm not mistaken this should solve the problem:
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider, description;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.providerId;
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
$scope.profileEmail = email;
//Set provider.
$scope.provider = provider;
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
description = descriptionSnapshot.val();
$scope.description = description;
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
});

Categories