Using localstorage to store login info - javascript

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

Related

I want to the signup form details and login using those details in localstorage with NodeJS

I'm trying for 5 days. I couldn't come up with the solution.I'm a student.
function createUser(){
let user_name = document.getElementById("name").value;
let user_ph = document.getElementById("tel").value;
let user_dob = document.getElementById("date").value;
let new_passwd = document.getElementById("new-password").value;
let user_passwd = document.getElementById("confirm-password").value;
let user_data = new Array();
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph!=user_ph}))
{user_data.push({
"user_name": user_name,
"user_ph": user_ph,
"user_dob": user_dob,
"user_passwd": user_passwd
})
alert("account created for this mobile number");
localStorage.setItem("users",JSON.stringify(user_data));
window.location.href="./login.html";
}
else
{
alert("This number is already linked with another account");
window.location.href = "./reg.html";
}
}
I tried this code and it actually store the data in array even with the empty data and the page don't go to the other page. It stays there.
function login(){
let user_tel = document.getElementById("tel").value;
let user_passwd = document.getElementById("password").value;
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph==user_ph && v.user_passwd==user_passwd})){
alert("welcome!");
//window.location.href="../profiles/home.html";
}
else
{
alert("Phone number and password is not right")
window.location.href="./login.html"
}
}
this is code for my login page

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

How to check if input exists in Firebase database

I have multiple booth users and I want to check if my username and password exists in a booth field.
Say I login using the username booth02 and password password. I want to return this as true/success.
This is my script:
router.post('/getlogin', function (req, res) {
username = req.body.username;
password = req.body.password;
adminlogin = database.ref('booths');
adminlogin.once('value', function(snapshot){
var dataSet = [];
snapshot.forEach(function(childsnapshot){
user = childsnapshot.val().username;
pass = childsnapshot.val().password;
if(username == user){
req.session.user = childsnapshot.key;
req.session.auth = true;
return res.status(200).send('Success');
}else{
return res.status(401).send('false');
}
});
})
})
But the result being returned for my user and pass is the first data which is username:booth01 and password:idontknow .
Is there a way to specifically return the data from Firebase based on my inputs?
Change this:
adminlogin.once('value', function(snapshot){
to this:
adminlogin.orderByChild("username").equalTo(inputname).once('value', function(snapshot){
the value inputname inside equalTo query will be the input that you entered in the form. Then it will only retrieve data that is related to the name of the user you entered.
more info here:
https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo

I keep getting the error unexpected token b in JSON at position 0 at JSON.parse?

So I got this code that creates a html page.The function signup allows the user to register and create a password. The function checkpassword is to check if the correct password is entered for the username.It seems I have a problem in getting the item from local storage in my checkPassword function?Help will be much appreciated as I've been stuck for hours?
const PREFIX = "monash.eng1003.passwordApp.";
function checkPassword() {
var user = document.getElementById("registerUsername").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var passwordToCheck = localStorage.getItem(PREFIX + user);
var passwordTwo = JSON.parse(passwordToCheck);
if (password != passwordTwo) {
alert("Don't hack" + user);
} else {
alert("Welcome" + user);
}
}
function signup() {
var user = document.getElementById("registerUsername").value;
var pass1 = document.getElementById("registerPassword").value;
var pass2 = document.getElementById("confirmPassword").value;
if ((pass1 === pass2) && (pass1 !== "")) {
if (localStorage) {
var passwordToStore = pass1;
localStorage.setItem(PREFIX + user, passwordToStore);
alert("Account created for username: " + user);
}
} else {
alert("Passwords must match and cannot be empty.")
}
}
EDIT:Thanks for pointing out that I do not need to parse it since I didn't stringify.That solved the problem but since I cannot delete the post I have to leave it here
You didn't convert the password to JSON when you stored it, so you don't need to use JSON.parse() when you retrieve it. You stored an ordinary string, you can just retrieve it and use it.
passwordTwo = localStorage.getItem(PREFIX + user);

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!"
}
}
}

Categories