How to restrict from sending null values into Firebase - javascript

I am trying to do a validation in firebase. However, even when I left the field blank and click submit, the null value is still submitted. How do I validate or change any security in a way that it will restrict any null values from saving into the database?
function save() {
window.location = 'profile.html';
var email = firebase.auth().currentUser.email;
var uid = firebase.auth().currentUser.uid;
var name = document.getElementById('name').value
var address = document.getElementById('address').value
var phone = document.getElementById('phone').value
var occupation = document.getElementById('TypeSelect').value
//One of the validation example
var name;
name = document.getElementById("name").value;
if (name == "") {
alert("Please enter your name");
};
var data = {
User_id: uid,
Name: name,
Address: address,
Phone: phone,
Email: email,
Occupation: occupation,
}
var updates = {};
updates['/users/' + uid] = data;
firebase.database().ref().update(updates);
}

A simple way is to only put items in data if they have a value:
var data = {};
if (uid) data.User_id = uid;
if (name) data.Name = name
if (address) data.Address = address;
if (phone) data.Phone = phone;
if (email) data.Email = email;
if (occupation) data.Occupation = occupation;

Related

How should I use localstorage for 2 things

As the title says, I want to use localstorage to store 2 things: accounts, and products and information of it. First, I got the accounts part working using this code:
function signup(e) {
event.preventDefault();
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var user = {
number: 1,
email: email,
username: username,
password: pass
};
var json = JSON.stringify(user);
localStorage.setItem(username, json);
}
function login(e) {
event.preventDefault();
var username = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var result = document.getElementById("result");
var user = localStorage.getItem(username);
var data = JSON.parse(user);
if (user == null) {
result.innerHTML = "Wrong Username";
} else if (username == data.username && pass == data.password) {
result.innerHTML = "Logged In";
for (var i = 0; i < localStorage.length; i++) {
var keys = Object.keys(localStorage);
var datas = JSON.parse(localStorage.getItem(keys[i]));
var datauser = datas.username;
datas.number = 2;
var jsonval = JSON.stringify(datas);
localStorage.removeItem(keys[i]);
localStorage.setItem(datauser, jsonval)
}
localStorage.removeItem(username);
data.number = 1;
var json = JSON.stringify(data);
localStorage.setItem(username, json);
} else {
result.innerHTML = "Wrong Password";
}
}
function getaccount() {
for (var i = 0; i < localStorage.length; i++) {
var keys = Object.keys(localStorage);
var data = JSON.parse(localStorage.getItem(keys[i]));
if (data.number == 1) {
document.getElementById("accountnamep").innerHTML = data.username;
document.getElementById("name").innerHTML = data.username;
}
}
}
and then I have a code for my products but I dont know how I would show it in a "your cart" file but the code I have currently is:
var tocart = {
name: name,
price: price,
size: size,
quantity: quantity,
shipping: shipping
};
var json = JSON.stringify(tocart);
localStorage.setItem(name, json);

How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. Where I am storing the user data in an array and then in local storage. For this I have initially declared an empty array called var users=[];
Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. Please help, on how to avoid the array become empty after reloading the page.
Following is my controller.js-
//Declaring an empty array
var users = [];
//Setting id for each users
var idInput = makeCounter();
//Fetching data from textboxes in register.html
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var dobInput = document.getElementById("dob");
var messageBox = document.getElementById("editeddata");
//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.dob = dob;
this.username = username;
this.password = password;
this.FullName = this.firstname +' ' + this.lastname;
}
//counter funtion, to fetch user id
function makeCounter() {
var arraylength=users.length;
return function(){
return arraylength+1;
}
}
//insert data while registration
function registerUser()
{
//Email validation
var emailinput = document.forms["myform"]["email"].value;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!(emailinput).match(emailReg) || emailinput=="")
{
alert("Not a valid e-mail address");
return false;
}
//check, if fields are empty
if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
{
alert("Fields cannot be empty");
return false;
}
//check, if a user already exist
var usernameinput = document.forms["myform"]["username"].value;
var passwordinput = document.forms["myform"]["password"].value;
var ulen= users.length;
for(i=0; i < ulen; i++)
{
if ( usernameinput == users[i].username && passwordinput == users[i].password)
{
alert("User already exists");
return false;
}
}
var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
users.push(user);
alert("Registered successfully");
localStorage.setItem("key_users", JSON.stringify(users));
}
You can use local storage value at the time of initialisation.
if (typeof(Storage) !== "undefined") {
if (localStorage.key_users) {
users = localStorage.key_users;
} else {
users = [];
}
}
you can use something like this to check if the key is already in localStorage or not.
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body onload="test()">
<script>
function test(){
var value = (localStorage.getItem("key1"))
console.log(value)
if(value == null){
localStorage.setItem("key1","value1")
alert("Hellow")
}else{
var value=localStorage.getItem("key1");
alert(value)
}
}
</script>
</body>
</html>

How to ignore empty fields in Ionic / Firebase?

I have a function for the user to be able to change his own details in his account like his description or social links etc...
However, when I submit the form, it replaces everything and the empty values just erase the field in the database.
Any way to submit the form and replace ONLY the values that have been entered in the field and ignore the empty ones ?
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 cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
var city = cityInput.value;
var age = ageInput.value;
var hobbies = hobbiesInput.value;
var facebook = facebookInput.value;
var twitter = twitterInput.value;
var instagram = instagramInput.value;
var youtube = youtubeInput.value;
var snapchat = snapchatInput.value;
var linkedin = linkedinInput.value;
var email = emailInput.value;
var password = passwordInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
city: city,
age: age,
hobbies: hobbies,
facebook: facebook,
twitter: twitter,
instagram: instagram,
youtube: youtube,
snapchat: snapchat,
linkedin: linkedin,
email: email,
password: password,
});
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");
});
}
});
var firebase_data = {};
var userID = firebase.auth().currentUser.uid;
var input_data = {
nameInput: document.querySelector('#name'),
descriptionInput: document.querySelector('#description'),
cityInput: document.querySelector('#city'),
ageInput: document.querySelector('#age'),
hobbiesInput: document.querySelector('#hobbies'),
facebookInput: document.querySelector('#facebook'),
twitterInput: document.querySelector('#twitter'),
instagramInput: document.querySelector('#instagram'),
youtubeInput: document.querySelector('#youtube'),
snapchatInput: document.querySelector('#snapchat'),
linkedinInput: document.querySelector('#linkedin'),
emailInput: document.querySelector('#email'),
passwordInput: document.querySelector('#password'),
saveButton: document.querySelector('#save')
}
for(var key in input_data) {
if(input_data.hasOwnProperty(key) && input_data[key].value.length) {
firebase_data[key] = input_data[key].value
}
}
firebase.database().ref('accounts/' + userId).set(firebase_data)
For the people, like me, that are new to this, here is the solution I found : Autocomplete the fields that have a value already so when I submit the form it is saved again with the same value.
The code :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
var database = firebase.database().ref('/accounts/' + userId);
// Retrieve information into the fields already filled in Database
database.on('value', function(snapshot) {
var displayName = snapshot.val().name;
var description = snapshot.val().description;
var displayCity = snapshot.val().city;
var displayAge = snapshot.val().age;
var displayHobbies = snapshot.val().hobbies;
var displayFacebook = snapshot.val().facebook;
var displayTwitter = snapshot.val().twitter;
var displayInstagram = snapshot.val().instagram;
var displayYoutube = snapshot.val().youtube;
var displaySnapchat = snapshot.val().snapchat;
var displayLinkedin = snapshot.val().linkedin;
var displayEmail = snapshot.val().email;
var displayPassword = snapshot.val().password;
$scope.$apply(function() {
$scope.displayName = displayName;
$scope.description = description;
$scope.displayCity = displayCity;
$scope.displayAge = displayAge;
$scope.displayHobbies = displayHobbies;
$scope.displayFacebook = displayFacebook;
$scope.displayTwitter = displayTwitter;
$scope.displayInstagram = displayInstagram;
$scope.displayYoutube = displayYoutube;
$scope.displaySnapchat = displaySnapchat;
$scope.displayLinkedin = displayLinkedin;
$scope.displayEmail = displayEmail;
$scope.displayPassword = displayPassword;
});
document.getElementById("name").value = displayName;
document.getElementById("description").value = description;
document.getElementById("city").value = displayCity;
document.getElementById("age").value = displayAge;
document.getElementById("hobbies").value = displayHobbies;
document.getElementById("facebook").value = displayFacebook;
document.getElementById("twitter").value = displayTwitter;
document.getElementById("instagram").value = displayInstagram;
document.getElementById("youtube").value = displayYoutube;
document.getElementById("snapchat").value = displaySnapchat;
document.getElementById("linkedin").value = displayLinkedin;
document.getElementById("email").value = displayEmail;
document.getElementById("password").value = displayPassword;
});;

can't get firebase userID

I am a newbie to firebase and Javascript and I have tried many methods get the user data store by the userid but all i'm getting is the data is being stored under "undefined".
here is my JS code
function handleRegister() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var ref = firebase.database().ref();
console.log(email);
console.log(fname);
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(user) {
var uid = user.uid;
var postData = {
Firstname: fname,
Lastname: lname,
email: email,
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('Users').push().uid;
var updates = {};
updates['/Users/' + newPostKey] = postData;
// updates['/user-posts/' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
})
}
What I'm trying to do is that after a new user has been registered, I want to save the user info(i.e first and last name) into the database under their respective uid generated during authentication.
but currently i can't get the uid and new user replaces previously entered user in DB instead of being entered as a new entry.
You're complicating things a bit, by combining parts from the samples.
Saving the user that has just registered takes this:
firebase.auth().createUserWithEmailAndPassword(email, password) .then(function(user) {
var root = firebase.database().ref();
var uid = user.uid;
var postData = {
Firstname: fname,
Lastname: lname,
email: email
};
root.child("Users").child(uid).set(postData);
})

IndexedBD and localStorage undefined error

I have an indexedDB which im trying to use to capture form information on user registration. That part is working fine but the prof wants an account to be create once with the username and password set on creation so he can log in.
The way I approached this was with a localStorage API. I created a function to check if the admin account had ever been created, and if not to create it calling the addAdmin() function.
I tried to create addAdmin() by copying my addObject() but for some reason my db variable is returning as undefined in the console.
Error" Uncaught TypeError: Cannot call method 'transaction' of undefined
var mainForm, fName, lName, uName, pass, email, dob, phone, bio, nl, terms, school, gender, save, reset, db;
//-------------USER DB------------------//
function startDB(){
mainForm = document.getElementById('mainFormSidebar');
fname = document.getElementById('fName');
lName = document.getElementById('lName');
users = document.getElementById('uName');
pass = document.getElementById('password');
email = document.getElementById('email');
dob = document.getElementById('dob');
phone = document.getElementById('phone');
bio = document.getElementById('bio');
nl = document.getElementById('newsletter');
terms = document.getElementById('terms');
school = document.getElementById('school');
gender = document.getElementsByName('gender');
save = document.getElementById('save');
reset = document.getElementById('reset');
reset.addEventListener('click',clearForm);
databox = document.getElementById('databox');
mainForm.addEventListener('submit',addObject);
//open DB
var request = indexedDB.open('macroPlay');
//if fails
request.addEventListener('error', showerror);
//if succeeds
request.addEventListener('success', start);
//if !exist, create.
request.addEventListener('upgradeneeded', createdb);
//Create Admin account on launch
chkAdmin();
}
function createdb(e){
var datababase = e.target.result;
var myusers = datababase.createObjectStore('users', {keyPath: 'userName'});
}
function start(e){
db = e.target.result;
showUsers();// Show all values in the object store
}
function addObject(){
if(confirm('Are you sure you want to resgister?')){
var fName = document.getElementById('fName').value;
var lName = document.getElementById('lName').value;
var userName = document.getElementById('uName').value;
var pass = document.getElementById('password').value;
var email = document.getElementById('email').value;
var dob = document.getElementById('dob').value;
var phone = document.getElementById('phone').value;
var bio = document.getElementById('bio').value;
var nl = document.getElementById('nl').value;
var terms = document.getElementById('terms').value;
var school = document.getElementById('school').value;
//May need to set a loop to find value of radio
var gender;
var radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.add(new getUser(userName,fName,lName,pass,email,dob,phone,bio,nl,terms,school,gender));
}
// Show all results.
mytransaction.addEventListener('complete', showUsers);
//Reset Form Fields
resetForm();
}
function getUser(userName, fn, ln, pw, em, dob, tel, bio, nl,tm, scl, gender){
this.userName = userName;
this.fn = fn;
this.ln = ln;
this.pw = pw;
this.em = em;
this.dob = dob;
this.tel = tel;
this.bio = bio;
this.nl = nl;
this.tm = tm;
this.scl = scl;
this.gender = gender;
}
//------Create Admin Account-----//
function chkAdmin(){
alert('before adding admin');
if(localStorage.getItem('admin')!="added"){
alert('adding admin');
addAdmin();
alert('admin added');
}
}
function addAdmin(){
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
var request = myusers.add(new getUser('admin','Shawn','Smith-Choa','admin'));
request.addEventListener('success',showUsers);
//Locally store that admin as been created
var admin = 'admin';
var value = 'added';
newItem(admin,value);
}
//-------------Web Storage API------------//
function newItem(id,style){
localStorage.setItem(id,style);
}
You're not assigning the value of db to anything so it's always undefined. I think you mean to be doing it in the createdb method, but really you should be capturing/assigning it in the start method which the success handler will trigger (I also can't find the start method anywhere)

Categories

Resources