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 );
}
}
});
Related
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
});
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 {
};
});
I've created a register and login for my website, and I've created a table to store the users first name and last name, but I want to store more than one user in the table, but every time I update the table, it replaces the first user every time a new user logs in.
Click the link to view the images:
https://imgur.com/a/CFMC8
/*-- REGISTER --*/
function storeUserDetail(){
var fNameInput = document.getElementById("firstNameInput").value;
var lNameInput = document.getElementById("lastNameInput").value;
var uNameInput = document.getElementById("userNameInput").value;
var pWordInput = document.getElementById("passWordInput").value;
if(fNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your First Name.</span>";
}
else if(lNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Last Name.</span>";
}
else if(uNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(pWordInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
var storeDetails = {};
storeDetails.FirstName =
document.getElementById("firstNameInput").value;
storeDetails.LastName =
document.getElementById("lastNameInput").value;
storeDetails.Username =
document.getElementById("userNameInput").value;
storeDetails.Password =
document.getElementById("passWordInput").value;
localStorage[storeDetails.Username] = JSON.stringify(storeDetails);
window.location.replace("http://localhost/login.php");
}
}
/*-- LOGIN -- */
function loginUser(){
var Username = document.getElementById("userNameInput").value;
var Password = document.getElementById("passWordInput").value;
if(Username === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(Password === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
if(localStorage[Username] === undefined) {
document.getElementById("logMessage").innerHTML = "<span
class='error'>Username Incorrect. Please try again.</span>";
return;
}
else {
var storeDetails = JSON.parse(localStorage[Username]);
if(Password === storeDetails.password) {
localStorage.loggedInUserName = storeDetails.Username;
window.location.replace("http://localhost/game.php");
}
else{
document.getElementById("logMessage").innerHTML = "<span
class='error'>Password Incorrect. Please try again.</span>";
}
}
}
/* TABLE */
function inputUserInfo(){
var storeDetails = JSON.parse(localStorage[localStorage.LoggedInUser]);
var table = document.getElementById("rankTable");
var row = table.insertRow();
var firstNameCell = row.insertCell(0);
var lastNameCell = row.insertCell(1);
firstNameCell.innerHTML = storeDetails.FirstName;
lastNameCell.innerHTML = storeDetails.LastName;
}
You can't create a registration and login system using local storage. Local storage only saves values in the user's own browser, thus 'local.' The server doesn't know about them, other users don't know about them, and they're all cleared a way if the user clears their browser history thoroughly. And there is only one value for each given key -- if you say username = "Sarah" today, and username = "Laura" tomorrow, then Laura overwrites Sarah, because it just doesn't make sense for the user's browser to have two different things both called username.
Local storage isn't suitable for registration and login systems. It's only suitable for caching things for an individual user. For example, you might store in-progress/unsent messages in local storage so the user doesn't lose them on a page refresh.
So I am new to web development and Firebase as well. I have been trying to build a multi page web app in simple javascript and firebase. App looks good and works for most of the part. Yet it is really of no use as I am having following issue :
When I sign in through googleAuthProvider (on my index.html page), I am taken to another page which is main.html . Now til here is fine. But once the main.html is loaded, it goes into a loop of continuous refreshing.
My rationale behind this is, that somehow Firebase is trying to re-authenticate the page on loading. And so the loop happens. But why, this I am not able to debug.
I have looked over almost everything I could find on internet but no where I could find a solution which is for simple javascript based multi page web app with firebase.
Here's a link to my app if anyone is interested and kind enough to have a look.
Chatbot
Also, here is my javascript code too.
var config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX"
};
firebase.initializeApp(config);
//===============================================================================================
$("document").ready(function(){
const signinGoogle = document.getElementById("googleAuth");
const signOut = document.getElementById("signout");
const sendMsg = document.getElementById("send");
const messageBox = document.getElementById("chatBox");
const displayNAME = document.getElementById("dipslayName");
const storageRef = firebase.storage().ref();
var currentUser;
var name;
var photoUrl;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initApp();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signinGoogle){
googleAuth.addEventListener('click', e=>{
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var tokenGoogle = result.credential.accessToken;
// The signed-in user info.
var userGoogle = result.user;
// ...Below line to be rmeooved if not working expectedly.
// var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signOut){
signout.addEventListener('click', e=>{
if(confirm("Do you wish to leave?")){
promise = firebase.auth().signOut().then(function(){
window.location = "index.html";
});
promise.catch(e =>
console.log(e.message))
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initApp(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
$("document").ready(function(){
currentUser = firebase.auth().currentUser;
name = currentUser.displayName;
photoUrl = currentUser.photoURL ;
console.log("Current user's name is : "+name);
console.log("Current user's photoUrl is : "+photoUrl);
displayNAME.innerHTML = "Hi "+name;
//+++++++++++Retrieving Msgs++++++++++++++++++++++++++++++++
var i=1;
var firebaseRetrieveRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseRetrieveRef.on("child_added", snap =>{
var retrievedMsg = snap.val();
console.log("retrieved msgs is : "+retrievedMsg);
$("#taskList").append("<li id='list"+i+"'><div style='width:100%'><img src='"+photoUrl+"'style='width:10px;height:10px;border-radius:5px;'/><label>"+name+"</label></div><div style='width:100%'><p>"+retrievedMsg+"</p></div></li>");
i++;
});
//+++++++++++Storing Msgs++++++++++++++++++++++++++++++++
$("#send").on("click", function(){
var newMessage=messageBox.value;
if(newMessage==""){
alert("Empty Message doesn't make any sense, does it?? ");
}
else{
var firebaseStoreRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseStoreRef.push().set(newMessage);
messageBox.value="";
}
});
//+++++++++++Clearing/deleting all tasks++++++++++++++++++++++++
$("#clear").on("click", function(){
var firebaseDeleteRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseDeleteRef.remove();
$( ".scrolls" ).empty();
});
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
}
else
{
console.log(user+" is not logged in");
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
You keep redirecting to main.html.
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
You keep redirecting to main.html whenever you determine the user is signed in. Make sure on main.html, you are not using the same logic and redirecting again.
(For what it's worth; I had this working, but for iOS compatibility, I've had to switch plugins)
Hopefully, this will be the last time I ask on this subject. I'm now using the following plugin for phonegap build:
<gap:plugin name="cordova-plugin-facebook4" source="npm">
For what it counts, on this version of the CLI:
<preference name="phonegap-version" value="cli-5.2.0" />
My login works fine, but it doesn't run the callback for the api function:
var fbLoginSuccess = function (response) {
alert ("success");
storage.setItem("user_auth",response.authResponse.accessToken); //get access token
user_auth = response.authResponse.accessToken;
login_data.auth_token = response.authResponse.accessToken; //get access token
login_data.account_id = response.authResponse.userID; //get facebookConnectPlugin UID
login_data.expires = response.authResponse.expiresIn; //get expire duration
login_data.socialmedia_name = 'facebook';
facebookConnectPlugin.api("/v2.3/me/?fields=id,email,first_name,last_name",["public_profile","email"], function(profileData) {
alert ("api success");
login_data.email = profileData.email;
login_data.display_name = profileData.first_name + " " + profileData.last_name;
//...
});
}
var fb_login = function() {
var login_data = {};
client.cmd = "login";
login_data.userid = user_id;
login_data.cmd = "login";
facebookConnectPlugin.login([
'public_profile',
'email',
'user_posts',
'user_photos',
'user_videos',
'user_friends'
], fbLoginSuccess,
function (error) {
console.error(error);
}
);
}
I've followed the guidance from this link to have another attempt like this:
var fbLoginSuccess = function (response) {
storage.setItem("user_auth",response.authResponse.accessToken); //get access token
user_auth = response.authResponse.accessToken;
login_data.auth_token = response.authResponse.accessToken; //get access token
login_data.account_id = response.authResponse.userID; //get facebookConnectPlugin UID
login_data.expires = response.authResponse.expiresIn; //get expire duration
login_data.socialmedia_name = 'facebook';
facebookConnectPlugin.api("/me",null,function(profileData) {
alert ("api success");
login_data.email = profileData.email;
login_data.display_name = profileData.first_name + " " + profileData.last_name;
//...
});
}
But no luck - I'm surely missing something very simple - what is it?