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.
Related
Okay so I've looked on YouTube, read tutorials and blog posts, what in lords name am I missing?
I am populating the following via firebase auth
auth.onAuthStateChanged(user => {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
console.log(uid); // <---- This works
// ...
} else {
// User is signed out.
// ...
}
});
console.log(uid); // <---- This doesn't
Now upon using console.log() and passing the variables to it, the correct outputs are received however I can't use the variables outwith that function.
I've looked and looked and the word "var" keeps re-appearing commonly attached to the word "global"
I tried declaring the variables outwith the function i.e.
uid = user.uid;
and
var uid;
declared above the function and the exact same result.
Can someone point out what very obvious thing I'm missing, I'm not asking for code to be re-written or anything of the sort! Just an explanation of the key concept I'm failing to grasp here.
Many thanks in advance!
You could try:
let uid = "";
let displayName = "";
let email = "";
const user = await auth.onAuthStateChanged(user => user ? user : null);
if (user) {
uid = user.uid;
displayName = user.displayName;
email = user.email;
}
console.log(uid);
i want to get user data from firebase after login. when I get the name from database it is providing value as undefined.. why?
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.userName;
var user = user;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
}
Remember that firebase auth saves only the following data:
email: 'user#example.com',
emailVerified: false,
phoneNumber: '+11234567890',
password: 'secretPassword',
displayName: 'John Doe',
photoURL: 'http://www.example.com/12345678/photo.png',
disabled: false
So user.userName doesn't exist.
You can use displayName to save the username but if you really use it to save the name you can create a node called users in firebase realtime database where you could save the username based on UID, something like this:
users
->akdjf231dkeimdla
->username: jamesbond007
After you code could be:
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.displayName;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
//Here are reading the username from the database
var username = snapshot.val().username;
});
}
If you use firebase realtime database remember to add the firebase realtime database library.
For more information: https://firebase.google.com/docs/auth/admin/manage-users
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 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´m want to check if the user who want to sign in using the facebook or google auth in to my web app is register on the real time database of firebase, so the idea is after the user press the button of sign in with facebook/google, first check in to the real time database if the uid is already on the real time database before redirect the user to another URL, for this i´m using the next function:
app.auth = function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var users_ref = firebase.database().ref('dream_wedding_users');
var register_user;
var register = false;
users_ref.on('value', function(snapshot) {
register_user = snapshot.val();
});
$.each(register_user, function(index, val){
if(user.uid === index){
register = true;
}
})
if(!register){
firebase.auth().signOut();
$('#login').modal('hide');
$('#modal_register').modal('show');
return false;
}else{
$(window).attr('location', 'http://localhost/wedding/en/gallery_en.php');
}
}
});
}
and for the auth function just the regular auth function for facebook and google that attach to a button.
app.facebook_login = function(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
console.log(error)
});
}
app.google_login = function(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
firebase.auth().signInWithRedirect(provider);
}).catch(function(error) {
console.log(error);
});
}
my problem is the next one, when i click sign in facebook or google, first login the user, then redirect the user, then check is the user is register on the real time data base and then logout the user if is not register and then show the modal. i don´t want that redirect the user i want that check if the user is register and then show the modal of "register" if the user is not register without redirect, and redirect if the user is register.
You want to add a unique user , if it is already not registered right ?
here is the valid way:
var usernew = result.additionalUserInfo.isNewUser
console.log('Is this a new user ? => ' + usernew );
complete code is as follows:
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var usernew = result.additionalUserInfo.isNewUser;
console.log('Is this a new user ? => ' + usernew );
if (usernew == true) {
NewUser();
}
var token = result.credential.accessToken;
user = result.user;
// alert(JSON.stringify(user.photoURL))
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
add user if it is not registered:
function NewUser(){
firebase.database().ref('/users').push({
Name : 'Johnson'
Age : '22'
})
}