User ID not posting to Firebase - javascript

I'm trying to allow logged-in users post a title and description with their Google ID to Firebase, but the user ID is giving an undefined error in the console.
The error is only triggered when addIdea() function is called, when the form is posted. Form elements are simply ng-models for title and desc.
var app = angular.module("fluttrApp", ["firebase"]);
app.controller("fluttrCtrl", function($scope, $firebase) {
var ref = new Firebase("[forge].firebaseio.com/ideas");
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (!user) {
auth.login('google', {
rememberMe: true
});
}
else {
console.log(user.displayName);
console.log(user.uid)
$scope.displayName = user.displayName;
$scope.uid = user.uid;
}
});
var sync = $firebase(ref);
$scope.ideas = sync.$asArray();
$scope.title = "";
$scope.desc = "";
$scope.addIdea = function(title, desc, uid) {
$scope.displayName = user.displayName;
$scope.uid = user.uid;
$scope.ideas.$add(
{
"title": title,
"desc": desc,
"user": uid
}
);
//The user id needs to be pulled and we need to post
//the idea id generated here to the user branch
$scope.title = '';
$scope.desc = '';
}
});

The object user is undefined because it is out of the scope of the $scope.addIdea() function.
It exists only in the callback of FirebaseSimpleLogin call.
Take a look at this example Monitoring Authentication for reference.

Related

Retrieving Firebase Child Value in Javascript

function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}

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'))
}

Sign in user if is register (Firebase facebook/google auth)

i´m want to check if the user who want to sign in using the facebook or google auth in to my web app is register on the real time database of firebase, so the idea is after the user press the button of sign in with facebook/google, first check in to the real time database if the uid is already on the real time database before redirect the user to another URL, for this i´m using the next function:
app.auth = function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var users_ref = firebase.database().ref('dream_wedding_users');
var register_user;
var register = false;
users_ref.on('value', function(snapshot) {
register_user = snapshot.val();
});
$.each(register_user, function(index, val){
if(user.uid === index){
register = true;
}
})
if(!register){
firebase.auth().signOut();
$('#login').modal('hide');
$('#modal_register').modal('show');
return false;
}else{
$(window).attr('location', 'http://localhost/wedding/en/gallery_en.php');
}
}
});
}
and for the auth function just the regular auth function for facebook and google that attach to a button.
app.facebook_login = function(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
console.log(error)
});
}
app.google_login = function(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
firebase.auth().signInWithRedirect(provider);
}).catch(function(error) {
console.log(error);
});
}
my problem is the next one, when i click sign in facebook or google, first login the user, then redirect the user, then check is the user is register on the real time data base and then logout the user if is not register and then show the modal. i don´t want that redirect the user i want that check if the user is register and then show the modal of "register" if the user is not register without redirect, and redirect if the user is register.
You want to add a unique user , if it is already not registered right ?
here is the valid way:
var usernew = result.additionalUserInfo.isNewUser
console.log('Is this a new user ? => ' + usernew );
complete code is as follows:
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var usernew = result.additionalUserInfo.isNewUser;
console.log('Is this a new user ? => ' + usernew );
if (usernew == true) {
NewUser();
}
var token = result.credential.accessToken;
user = result.user;
// alert(JSON.stringify(user.photoURL))
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
add user if it is not registered:
function NewUser(){
firebase.database().ref('/users').push({
Name : 'Johnson'
Age : '22'
})
}

Data not updating in Firebase and Ionic

I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?
Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}

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