Accessing child node properties in Firebase RTD - javascript

I have .js file where I loop through Firebase real time database to find email and password of registered users which is stored under /users tree in database where each child is randomly generated unique id which has user information. I am getting email and password information from form element. Problem is the alert messages in checkMessage are not executed when email and password do not equal same. Alert message should be displayed but only page refreshes.
Database:
----/Users
--------/XJIGFDMDKGD
-------------email: "a#b.com"
-------------password: "12345"
--------/XJFGNRIENGJ
-------------email: "c#d.com"
-------------password: "67890"
My code:
document
.getElementById('loginForm')
.addEventListener('submit', formSubmit);
function formSubmit(e) {
e.preventDefault();
document.querySelector('.alert').style.display = 'block';
// Get Values from the DOM
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
//check message values
checkMessage(email, password);
//Form Reset After Submission
//document.getElementById('loginForm').reset();
}
checkMessage function:
function checkMessage(email, password) {
var usrs = firebase.database().ref('users');
usrs.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.email == email) {
if (user.password == password) {
} else {
}
} else {
document.querySelector('.alert2').style.display = 'block';
setTimeout(function() {
document.querySelector('.alert2').style.display = 'none';
}, 7000);
document.getElementById('loginForm').reset();
}
);
}

The error was caused by syntax problem, an extra brace at the end of the following section of code, as well as a misplaced parentheses. Fixed solution:
var users = firebase.database().ref('users');
users.on("child_added", function(snapshot) {
var user = snapshot.val();
if (email == user.email) {
if (password == user.password) {
}
} else {
};
});

Related

JavaScript stops working when I refresh page

I have this block of JavaScript code:
var input = document.getElementById("password_field");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("login").click();
}
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if(user != null) {
var email_id = user.email;
var email_verified = user.emailVerified;
document.getElementById('user_para').innerHTML = "You are logged in as<strong> " + email_id + "</strong>.";
if (email_verified === false) {
document.getElementById('user_verified').innerHTML = "<strong>You are not verified. Please check for an email from perason for a verification link. You will not be able to access anything without verification.";
} else {
document.getElementById('user_verified').innerHTML = "";
document.getElementById('sandboxaccess').style.display = "block";
}
}
} else {
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login () {
var userEmail = document.getElementById('email_field').value;
var userPass = document.getElementById('password_field').value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
firebase.auth().signOut();
}
It works fine initially, but when I refresh the page, all of the JavaScript stops working. It works perfectly fine on Apache localhost (refreshing works on localhost too). What is the solution to this?
Here it is before refresh:
before refresh
Here it is after refresh:
after refresh
The logout button is in both.
Errors on console
Remove this line of code from your program:
var user = firebase.auth().currentUser
You already have a user object as the parameter of your callback function. The currentUser returned here might actually be wrongly null and overwriting the correct one being passed in.
I think the code is executed before the DOM is loaded.
how about this:
document.addEventListener('DOMContentLoaded', function (){
// your code
});

javascript redirection doesnt seem to work

I use JavaScript for a simple function, however my redirection doesn't work. I thought it was because of the files, but they seem to be in the same folder. See below file structure:
Here is my relevant code:
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "mr.X" && password == "x123456") {
alert("Login successfully");
window.location = "Dashboard.jsp"; // Redirecting to other page.
return false;
} else {
alert("You have inserted wrong credentials");
}
}

Check if user auth id exist in firebase database before navigating to a new page

After a user sign in successfully, I want to use the User UID to verify the user has selected the right school, I have been able to achieve this task, but the problem is, I have to click the login button twice before an action takes effect.
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
}
It is very unusual to have an onAuthStateChanged listener in a click handler like that. More likely you want something like:
...
} else {
toggleSignIn();
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
By the way: if you can look up the school for the user with a query, is there any specific reason why you don't simply prepopulate that value for them in the form?
Your code has a flaw. onAuthStateChanged listener is attached every time the button is clicked. This could add multiple listeners and the same code triggered multiple times after each repeated click. onAuthStateChanged listener should be attached only once when the document is loaded. Your code should be something like:
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
}
}
document.onload = function () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
I assume toggleSignIn() function is used to sign in and will change the firebase AuthState on successful sign in.

Data retrieval query for firebase not working

Above is the db structure and below is the code to retrieve the data from firebase database, I am unable to get the data from my db.I need help in retrieving the data from my firebase db.I have attached the database image for the view of my db.
function check(userId,snapcity){
var rootRef=firebase.database().ref().child('users');
rootRef.on('child_added', function(snap){
if(snap.child("userId").val()==userId){
snapcity=snap.child("city").val();
}
});
console.log(snapcity);
console.log(ajaxData.geoplugin_city);
if(snapcity){
if(snapcity!=ajaxData.geoplugin_city){
logout();
alert("you can't login because previously you were logged from "+snapcity );
}
}
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
userId=user.uid;
//alert(userId);
var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
datetime=n+" "+time;
snapcity="";
check(userId,snapcity);
var database = firebase.database();
writeUserData(userId,ajaxData.geoplugin_request,ajaxData.geoplugin_city,datetime);
document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
console.log('data');
console.log(ajaxData);
html="<p>ip: "+ajaxData.geoplugin_request+"</p><p>Country Code: +44</p><p>Country: "+ajaxData.geoplugin_countryName+"</p><p>Country Abbrevation: "+ajaxData.geoplugin_countryCode+"</p><p>Region Code: "+ajaxData.geoplugin_regionCode+"</p><p>Region Name: "+ajaxData.geoplugin_regionName+"</p><p>City: "+ajaxData.geoplugin_city+"</p><p>Time Zone: "+ajaxData.geoplugin_timezone+"</p><p>Latitude: "+ajaxData.geoplugin_latitude+"</p><p>Longitude: "+ajaxData.geoplugin_longitude+"</p><p>Last Login: "+datetime+"</p>";
$('#data').html(html);
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
[1]: https://i.stack.imgur.com/JVeRD.jpg
This:
rootRef.on('child_added', function(snap){
if(snap.child("userId").val()==userId){
snapcity=snap.child("city").val();
}
});
Can be replaces by:
rootRef.child(userId).once('value', function(snap){
snapcity = snap.child("city").val();
});
Next you need to move all code that needs snapcity into the callback function. So:
rootRef.child(userId).once('value', function(snap){
snapcity = snap.child("city").val();
console.log(snapcity, ajaxData.geoplugin_city);
if(snapcity){
if(snapcity!=ajaxData.geoplugin_city){
logout();
alert("you can't login because previously you were logged from: "+snapcity );
}
}
});

i need help for login page

I need help for a login page using JavaScript. So far I have following code:
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
// Like you must login to see the page
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
I want it like after login show the page like you must login to see the page.
Any ideas?
Your function should look like this if you want to redirect user to your home page after checking the username.
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
window.location.href = "your page url";
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
Note: this is not a way to handle authentication.

Categories

Resources