can't get firebase userID - javascript

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

Related

managing sessions on login nodejs

I am trying to manage user sessions in nodejs. I have built a dashboard where people will be able to manage their products for inventory and such. I basically have it running right now where a user logs in, and it stores there username in a global variable, and then userAuth gets set to true. Obviously in a prod env this would not work, so I am trying to manage each session. the user should log on, and they should have their own session, and all their database creds should be pulled from my master table, and then used for that specific session. multiple users should be able to use this and edit their products and inventory at the same time. I have tried express-session, but no luck, I'm doing something wrong but not sure where to start really. here's my login code:
//LOGIN FUNCTIONALITY
app.post("/login", (req, res) => {
//defining variables for users username & password inputs
const inputUsername = req.body.inputUsername;
const inputPassword = req.body.inputPassword;
//functionality to query db by username
var userLogin = "select * from login where USERNAME = ?";
ibmdb.open(ibmdbconnMaster, function (err, conn) {
if (err) return console.log(err);
conn.query(userLogin, [inputUsername], function (err, rows) {
if (err) {
console.log(err);
}
//if the query returns results that are > 0
if (rows.length > 0) {
var pass = "";
userSessionId = req.body.sessionID
var sessUsername = userUsername
//loop for getting those values that correspond with the username of the user
for (var i = 0; i < rows.length; i++) {
userUsername = rows[i]["USERNAME"];
pass = rows[i]["PASSWORD"];
firstName = rows[i]["FN"];
lastName = rows[i]["LN"];
company = rows[i]["COMPANY"];
ibmdbconnDash = rows[i]["DBCONNSTRINGDASH"];
ibmdbconnBlog = rows[i]["DBCONNSTRINGBLOG"];
mailerStatus = rows[i]["MAILERSTATUS"];
//these will be more secure when time comes
cloudinaryName = rows[i]["CLOUDINARYNAME"];
cloudinaryKey = rows[i]["CLOUDINARYKEY"];
cloudinarySecret = rows[i]["CLOUDINARYSECRET"];
}
//comparing user input password to hashed db password
bcrypt.compare(inputPassword, pass, function (err, result) {
console.log("result is " + result);
//if the result of the compare is true, then redirect to the index function
if (result == true) {
console.log("login works");
userAuth = "true"
res.redirect("/index");
} else {
//if compare returns false, re-render login page
userAuth = "false";
res.render("login.ejs");
alert("Incorrect username or password. Please try again");
}
});
//if the entire query returns rows < 1 (username and password don't match, then re-render login page)
} else {
userAuth = "false";
res.render("login.ejs");
alert("Incorrect username or password. Please try again");
}
conn.close(function () {
console.log("closed the function /login");
});
});
});
});
global variables
var userAuth = ""
var userName = "";
var firstName = "";
var lastName = "";
var company = "";
var password = "";
var ibmdbconnMaster =
"db2 conn string";
var ibmdbconnDash = "";
var ibmdbconnBlog = "";
var userUsername = "";
var mailerStatus = "";
var cloudinaryName = "";
var cloudinaryKey = "";
var cloudinarySecret = "";
I have tried implementing sessions using express-sessions, the code I had set up for that was the standard code from their site:
app.use(session({
secret: "sec",
resave: false,
uninitialized: true,
}))
main index / landing page (dashboard) function
//DEFINING GLOBAL VARIABLES FOR AUTH
var sessionID = "";
var numOfOrders = "";
var numOfUsersM = "";
var userAuth = ""
var userName = "";
var firstName = "";
var lastName = "";
var company = "";
var password = "";
var ibmdbconnMaster =
"db conn string";
var ibmdbconnDash = "";
var ibmdbconnBlog = "";
var userUsername = "";
var mailerStatus = "";
var cloudinaryName = "";
var cloudinaryKey = "";
var cloudinarySecret = "";
//manage sessions
app.use(session({
secret: 'secret-key',
resave: true,
saveUninitialized: true,
}))
//rendering login page
app.get("/login", (req, res) => {
res.render("login.ejs");
});
/
//LOGIN FUNCTIONALITY
app.post("/login", (req, res) => {
// console.log("sessionsid is: " + req.body.sessionID)
// sessionID = req.body.sessionID
//defining variables for users username & password inputs
const inputUsername = req.body.inputUsername;
const inputPassword = req.body.inputPassword;
//functionality to query db by username
var userLogin = "select * from login where USERNAME = ?";
ibmdb.open(ibmdbconnMaster, function (err, conn) {
if (err) return console.log(err);
conn.query(userLogin, [inputUsername], function (err, rows) {
if (err) {
console.log(err);
}
//if the query returns results that are > 0
if (rows.length > 0) {
var pass = "";
//var userUsername = ""
userSessionId = req.body.sessionID
var sessUsername = userUsername
//loop for getting those values that correspond with the username of the user
for (var i = 0; i < rows.length; i++) {
var userUsername1 = rows[i]["USERNAME"];
pass = rows[i]["PASSWORD"];
firstName = rows[i]["FN"];
lastName = rows[i]["LN"];
company = rows[i]["COMPANY"];
ibmdbconnDash = rows[i]["DBCONNSTRINGDASH"];
ibmdbconnBlog = rows[i]["DBCONNSTRINGBLOG"];
mailerStatus = rows[i]["MAILERSTATUS"];
cloudinaryName = rows[i]["CLOUDINARYNAME"];
cloudinaryKey = rows[i]["CLOUDINARYKEY"];
cloudinarySecret = rows[i]["CLOUDINARYSECRET"];
}
//comparing user input password to hashed db password
bcrypt.compare(inputPassword, pass, function (err, result) {
console.log("result is " + result);
//if the result of the compare is true, then redirect to the index function
if (result == true) {
console.log("login works");
var userAuth1 = "true"
//successful login
req.session.user = {
userUsername1,
userAuth1
}
console.log("rquu1 " + req.session.user.userUsername1)
res.redirect("/index");
} else {
//if compare returns false, re-render login page
userAuth1 = "false";
res.render("login.ejs");
alert("Incorrect username or password. Please try again");
}
});
//if the entire query returns rows < 1 (username and password don't match, then re-render login page)
} else {
userAuth = "false";
res.render("login.ejs");
alert("Incorrect username or password. Please try again");
}
conn.close(function () {
console.log("closed the function /login");
});
});
});
});
//function for logout page
app.get("/logout", (req, res) => {
userAuth = "false";
res.render("login.ejs");
});
//RENDERING INDEX PAGE WITH INFORMATION ABOUT PRODUCTS AND ANALYTICS
app.get("/index", (req, res) => {
// if (userAuth == "true") {
if (req.session.user) {
console.log(req.session.user)
console.log("username is: " + userName);
pageName = "/index";
numOfOrdersFun(req, res, numOfOrders)
//end of location manager
//initializing counter
var counterTest2 = "select * from VISITORS";
ibmdb.open(ibmdbconnDash, function (err, conn) {
if (err) return console.log(err);
conn.query(counterTest2, function (err, rows) {
if (err) {
console.log(err);
}
for (var i = 0; i < rows.length; i++) {
var dbCountCurrent = rows[i]["NUM"];
}
console.log("currentCount " + dbCountCurrent);
conn.close(function () {
console.log("closed the function /login");
});
//showing information for products
var showingDBINFO = "SELECT * FROM PRODUCTS";
ibmdb.open(ibmdbconnDash, function (err, conn) {
if (err) return console.log(err);
conn.query(showingDBINFO, function (err, rows) {
if (err) {
console.log(err);
}
//rendering page with all users information, products, and data from login. also a redirect from the login info.
res.render("index", {
page_title: "index",
data: rows,
userName: userName,
FN: firstName,
LN: lastName,
CO: company,
dbcc: dbCountCurrent,
numOfOrders: numOfOrders,
mailerStatus: mailerStatus,
});
conn.close(function () {
console.log("closed the function /index);
});
});
});
});
});
} else {
req.session.user.userAuth1 == "false"
res.render("login.ejs");
}
});
but now im confused on how to manage each session individually when their are so many global variables I have that are needed for each session, and would users be able to use the app simultaneously?
thanks for the help!
When using express-session you can use the req.session object and store your preferred data. In your concrete example you could set all the information about the user you need later in your code to req.session.user.
Tiny example:
//successful login
req.session.user = {
userName,
firstName
}
If you need to access any information about the user later, just use req.session.user.userName for instance.
This data is stored server-side and is also available in new requests.
Please also note that the secret shouldn't be the default, instead use a strong & generated password nobody knows.

How to restrict from sending null values into Firebase

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;

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 make a simple webpage register form using cookies? (jQuery)

I'm making a register/login form in javascript. User should enter information about himself and the computer should put that information into an array and remember it but it 'forgets' it every time I reload the page.
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
...more code
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
Any ideas to solve this? I have one more question. How can I check weather is an username alerady in use?
Here is the full js code:
var main = function() {
var people = [];
var cookies = [];
$('#register_email').val("");
$('#register_username').val("");
$('#register_password').val("");
$('#register2_password').val("");
function Person(username, email, password, repeat_password) {
this.username = username;
this.email = email;
this.password = password;
this.repeat_password = repeat_password;
}
$('#register').click(function() {
var username = $('#register_username').val();
var email = $('#register_email').val();
var password = $('#register_password').val();
var r_password = $('#register2_password').val();
if( email==="" || username==="" || password==="" || r_password==="") {
$('#error').text("You didn't fill everything");
}
else {
people[people.length] = new Person(username, email, password, r_password);
for(var key in people) {
//This should check weather this username was used before but I'm not really sure what to insert instead of "name"
if(people[people.length - 1].username === "name") {
$('#error').text("This username is already in use");
break;
}
else if(password !== r_password) {
$('#error').text("Passwords don't match");
break;
}
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
}
}
});
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
};
$(document).ready(main);
There is a js-fiddle live example in comments.

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