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
Related
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.
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");
})
})
}
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'))
}
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!"
}
}
}
I am trying to make and store usernames and passwords in cleartext. I am not doing any type of authentication (I know I could be using node passport to do this, and encrypting, but I am just learning javascript, so I am just trying to play around)
I have an object that I have globally defined like this:
var obj= {username: req.body.username,
password: req.body.password}
that I am pushing onto my registeredUsers array:
var registeredUsers = new Array();
My issue is that I want to be able to do something like:
if((($.inArray(username, registerdUsers) == username &&
($.inArray(password, registerdUsers)) == password){
res.redirect("/?error=Already Registered");
}
This doesn't work, how can I check both values of my object to see if they are contained in my array?
Here are the functions that I am doing the authentication in case anyone is curious:
function ensureAuthentication(req, res, next){
//push object onto the registeredUsers array
registeredUsers.push(obj);
//if the user is already registered, throw error
if (($.inArray(username, registeredUsers) && ($.inArray(password, registeredUsers)) {//obj.contains() username){
res.redirect("/?error=Already Registered");
}
//if new user
else{
authentication.push(obj);
console.log("added new user);
//redirect to homepage
res.rediret("/");
}
}
and
function login(req, res) {
//var username = req.body.username;
req.session.username = username;
req.session.password = password;
loggedInUsers[username] = LoggedIn;
if((($.inArray(username, registerdUsers) == username && ($.inArray(password, registerdUsers)) == password){
//increase login count
for(users in loggedInUsers){
++loginCount;
console.log("Login Count: ", loginCount);
}
//redirect to login page
res.redirect("/users")
}
else{
//print out error message
res.redirect("/?error=Error: incorrect username/password");
}
}
Find the object by username:
var user;
for(var i = 0; user = registeredUsers[i]; i++) {
if(user.username === username)
break;
}
Check the password:
var valid = user && user.password === password;
$.inArray is like Java's indexOf function which returns the index of the position if the obj is in the array, otherwise -1
So something like..
if((($.inArray(username, registerdUsers) !== -1 &&
($.inArray(password, registerdUsers)) !== -1){
res.redirect("/?error=Already Registered");
}
..would check to make sure you don't have any duplicate users with the exact same password, but allow duplicate users.
I think you are looking for something like..
if($.inArray(username, registeredUsers) !== -1){
res.redirect("/?error=Already Registered");
}
which says, if the username exists in the registeredUsers array, then give the error msg 'Already Registered'