Firebase realtime database error: user is null - javascript

I want read firebase realtimedatabse data and result is an error: user is null and other error, it's another method to do this, i cannot read file in firebase realtime database
auth.onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
console.log('login-form.js | logged')
const logged = true;
showHomepage();
const auth2 = firebase.auth()
const user = auth2.currentUser;
var email = user.email
console.log(email)
var namee = email
namee = namee.replace('.','')
namee = namee.replace('$','')
namee = namee.replace('#','')
namee = namee.replace('/','')
namee = namee.replace('[','')
namee = namee.replace(']','')
console.log(namee)
var ref = db.ref("/Utenti/" + namee + '/');
ref.on("value", function(data, prevChildKey) {
const user = data.val();
console.log(user.soldi)
document.getElementById('money').innerHTML = user.soldi + '€'
}, function (error) {
console.log("Error: " + error.code);
});
}
});

In your case, you can get user data (email, uid, ...) from firebaseUser variable, without calling firebase.auth().currentUser
firebase.auth().onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var email = firebaseUser.email;
var namee = email;
// ...
} else {
// User is signed out
// ...
}
});
Also, your screenshot and your code, it seems like the issue is that your auth function don't return user data, not that it cannot get user data from firebase. You can use a wrapper function to wrap outside your firebase.auth().onStateChanged() call, with a callback function, to get and return firebase user data:
export const firebaseWrapper = (callback) => {
firebase.auth().onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var email = firebaseUser.email;
var namee = email;
// ...
callback(firebaseUser);
} else {
// User is signed out
// ...
callback(null);
}
});
}
This callback() function can be a dispatch function, or a setState() or equivalent, depending on what you need.

Related

Error : Function CollectionReference.doc() cannot be called with an empty path

This is the javascript code I was running and ended up in getting this error in the javascript console:
Error : Function CollectionReference.doc() cannot be called with an empty path
Other people did answer the same question, but it didn't work in my case.
const firebaseApp = firebase.initializeApp({
// my configuration here
});
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
console.log("Logged in");
// ...
} else {
// User is signed out
// ...
alert("you are not logged in");
window.location.href = "Auth.html";
}
});
const Publish = () => {
const user = firebase.auth().currentUser;
// const displayName = user.displayName;
const email_value = user.email;
// const photoURL = user.photoURL;
// const emailVerified = user.emailVerified;
// const uid = user.uid;
let blogTitle = document.getElementById("exampleFormControlInput1").value;
let articleField = document.getElementById("exampleFormControlTextarea1").value;
var docName = blogTitle.toString()
db.collection(email_value).doc(docName).set({
title: docName,
article: articleField,
})
}
I tried the solutions given by other people like -- ${docName} but that didn't work. I am really confused at this point and don't know what I did wrong with the javascript.

Is there a library for promptForCredentials with firebase?

I am trying to learn how to delete users from the Firebase Auth provided, but when I click on the delete button on my html it gives me Uncaught ReferenceError: promptForCredentials is not defined
I can't find any information on if I am suppose to import it anywhere. I'm using plain vanilla javascript.
Here is my code:
my html includes for scripts:
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-database.js"></script>
javascript:
const firebaseConfig = {//my app information}
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const database = firebase.database();
const fname = document.querySelector('#fname');
const lname = document.querySelector('#lname');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const confirm_password = document.querySelector('#confirmpassword');
const deleteConfirmed = document.querySelector('.deleteConfirmed');
const passConfirmed = document.querySelector('#deletePass');
auth.onAuthStateChanged(user => {
if(user) {
const user = auth.currentUser
const database_ref = database.ref('users/' + user.uid).on('value', (snapshot) => {
fname.value = snapshot.val().first_name;
lname.value = snapshot.val().last_name;
email.value = snapshot.val().email;
});
deleteConfirmed.addEventListener('click', () => {
const credential = promptForCredentials();
user.reauthenticateWithCredential(credential).then(() => {
// User re-authenticated.
}).catch((error) => {
// An error ocurred
// ...
});
})
} else {
location.href = "/login";
}
});
It looks like you copied code from the Firebase documentation on re-authenticating a user, which shows:
const user = firebase.auth().currentUser;
// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();
user.reauthenticateWithCredential(credential).then(() => {
// User re-authenticated.
}).catch((error) => {
// An error occurred
// ...
});
That TODO there means that you have to implement the prompt for the credentials of the user in whatever way works for your app, and then pass them to the reauthenticateWithCredential API.

My web is not sending email verification via Firebase but my then function or error functions not triggering

I am working on html and java script project but when i try sendSignInLinkToEmail its not sending the email and both then and catch are not triggering
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const database = getDatabase(app);
const auth = getAuth();
var attachment = document.getElementById('attachment');
attachment.onchange = () => {
const selectedFile = attachment.files[0];
}
register.addEventListener('click', (e) => {
var fname = document.getElementById("fname-field").value;
var lname = document.getElementById("lname-field").value;
var birthdate = document.getElementById("birthdate-field").value;
var passport = document.getElementById("passport-field").value;
var email = document.getElementById("email-field").value;
var areacode = document.getElementById("country-select").value;
var phoneNumber = document.getElementById("phonenumber-field").value;
var country = document.getElementById("country-field");
var nation = document.getElementById("nation-field").value;
var emergencyname = document.getElementById("emergencyname-field").value;
var emergencyrelation = document.getElementById("emergencyrelation-field").value;
var emergencyinfo = document.getElementById("emergencyinfo-field").value;
var attachment = document.getElementById('attachment');
var persentage = document.getElementById('persentage');
createUserWithEmailAndPassword(auth, email, nation)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
set(ref(database, 'users/' + user.uid), {
FirstName: fname,
LastName: lname,
Birthdate: birthdate,
PassportNumber: passport,
Email: email,
PhoneNumber: phoneNumber,
Country: country,
Nationality: nation,
EmergencyName: emergencyname,
EmergencyRelation: emergencyrelation,
EmergencyInfo: emergencyinfo
});
async function UploadAttachment() {
var selectedFile = attachment.files[0];
var fileName = user.uid
const metaData = {
contentType: selectedFile.type
}
const storage = getStorage();
const storageRef = sRef(storage, "attachments/" + fileName)
const UploadTask = uploadBytesResumable(storageRef, selectedFile, metaData);
UploadTask.on('state-changed', (snapshot) => {
var uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
persentage.innerHTML = "Upload" + uploadProgress + "%";
},(error) => {
alert('error: Image Not Uploaded')
},
()=>{
getDownloadURL(UploadTask.snapshot.ref).then((downloadUrl) => {
console.log(downloadUrl);
})
}
);
}
UploadAttachment();
// ...
console.log("usersigned up");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
alert(errorMessage);
});
const actionCodeSettings = {
// URL you want to redirect back to. The domain (www.example.com) for this
// URL must be in the authorized domains list in the Firebase Console.
// This must be true.
handleCodeInApp: true,
};
sendSignInLinkToEmail(auth, email, actionCodeSettings)
.then(() => {
// The link was successfully sent. Inform the user.
// Save the email locally so you don't need to ask the user for it again
// if they open the link on the same device.
console.log("Email Sent");
window.localStorage.setItem('emailForSignIn', email);
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
}
);
});
You may have forgotten to add actionCodeSettings parameter to sendSignInLinkToEmail
If not try to
Use devtools breakpoints
Check network tab if there is any requests are going to server

firebase returns undefined user id at one place and the correct value at other

I have the following function to get the user id:
currentUser.js
import firebase from './firebase';
export default function getCurrentUserID() {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
// this value to authenticate with your backend server, if
// you have one. Use User.getToken() instead.
return uid;
}
return uid;
}
The following code to enable adding projects using the button, works fine:
addProject.js
import getCurrentUserID from './currentUserID';
import getFirestoreDB from './firestoreDB';
import Project from './project';
const addProjectBtn = document.getElementById('addProjectBtn');
function addProject() {
const title = prompt('Insert title');
const description = prompt('Insert Description');
const project = new Project(title, description);
const db = getFirestoreDB();
const currentUserUID = getCurrentUserID();
alert(currentUserUID);
db.doc(`users/${currentUserUID}/projects/${title}`).set({ ...project }).then(() => {
alert("Success");
}).catch((error) => {
alert("Error " + error);
});
}
export default function enableAddProjectBtnFunctionality() {
addProjectBtn.addEventListener('click', addProject);
}
But, the following code to display projects, doesn't work. The alert(uid) shows undefined here but shows the correct user id above.
displayProjects.js
import getCurrentUserID from "./currentUserID";
import getFirestoreDB from './firestoreDB';
var db = getFirestoreDB();
export default function displayProjects(){
var uid = getCurrentUserID();
if(uid){
alert(uid);
var projectsRef = db.collection("users").doc(`${uid}`).collection("projects");
projectsRef.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
}
}
Could someone help me figure out what's the problem here and how I could fix it?
Most likely the displayProjects method is executed before the user sign-in has been completed.
The proper way to pick up the user state in such scenarios is to use an auth state listener as shown in the first code fragment in the documentation on getting the current user.
In your code that'd look like this:
export default function displayProjects(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var uid = user.uid;
var projectsRef = db.collection("users").doc(`${uid}`).collection("projects");
projectsRef.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
});
}
});
}

Firebase Web creating user and write data in Real time database not working correct

Im assuming a strange behaviour while creating an account. I don't have an error to show, but sometimes firebase is not creating the user, sometimes firebase creates the user, but it not writes any data in realtime database. Pls someone help me out..
function signUp() {
var userArtistName = document.getElementById("userArtistName").value;
var userEmail = document.getElementById("userEmail").value;
var userPassword = document.getElementById("userPassword").value;
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
var firebaseRef = firebase.database().ref();
var userData = {
userArtistName: userArtistName,
userEmail: userEmail,
userIsArtist: true,
userId: uid,
}
firebaseRef.child('users/' + uid).set(userData);
console.log('User successfully created!');
// code for replace user
}).catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
my html form:
<form action="#">
<h1>Hello Form</h1>
<span>Register now</span>
<input type="text" placeholder="Name" id="userArtistName"/>
<input type="email" placeholder="Email" id="userEmail" />
<input type="password" placeholder="Password" id="userPassword" />
<button onclick="signUp()">Registrieren</button>
</form>
fb rules:
My firebase.js file:
// Your web app's Firebase configuration
var firebaseConfig = {
//fb config here
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a reference to firebase authenthification
const auth = firebase.auth();
function signUp() {
var userArtistName = document.getElementById("userArtistName").value;
var userEmail = document.getElementById("userEmail").value;
var userPassword = document.getElementById("userPassword").value;
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
var firebaseRef = firebase.database().ref();
var userData = {
userArtistName: userArtistName,
userEmail: userEmail,
userIsArtist: true,
userId: uid,
}
firebaseRef.child('users/' + uid).set(userData);
console.log('User successfully created!');
// code for replace user
}).catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
function signIn() {
var email = document.getElementById("txtEmail");
var password = document.getElementById("txtPassword");
auth.signInWithEmailAndPassword(email.value, password.value)
.then(userCredential => {
const userId = userCredential.user.uid;
return firebase.database().ref('/users/' + userId).once('value')
})
.then(snapshot => {
var userIsArtist = snapshot.val().userIsArtist;
if (!userIsArtist) {
//Redirect to login or other action or message
//signOut();
console.log(userIsArtist);
} else {
window.location.replace("main.html");
}});
// }).catch((error) => {
// // Handle Errors here.
// // .catch function to hide error in console. error tells UID actually. We don't want that
// var errorCode = error.code;
// var errorMessage = error.message;
// });
}
function signOut() {
auth.signOut()
console.log('Successfully signed out!');
window.location.replace('login.html');
}
auth.onAuthStateChanged(function (user) {
if (user) {
let user = firebase.auth().currentUser;
if(user != null){
// deactivating loading spinner for people, who are not logged in
document.getElementById("login-cover").style.display = "none";
}
var email = user.email;
document.getElementById('fb-email').innerHTML = "Welcome User : " + email;
console.log('Successfully logged in! ---- Active User: ' + email);
} else if (
// Not signed in, redirecting to login page
user == null &&
window.location.href == 'http://localhost/www.muego.com/main.html' ||
window.location.href == 'http://localhost/www.muego.com/songs.html') {
// Redirect user because session is not valid anymore
window.location.replace('login.html');
}
});
function resetPassword() {
var auth = firebase.auth();
var emailAddress = "admin#trash-mail.com";
auth.sendPasswordResetEmail(emailAddress).then(function () {
// Email sent.
}).catch(function (error) {
// An error happened.
});
}
after several hours of try and error and with much love and help of #Dharmaraj the final code looks like this:
function createAccount(){
var userEmail = document.getElementById("userEmail").value;
var userPass = document.getElementById("userPassword").value;
var userArtistName = document.getElementById("userArtist").value;
firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).then(function() {
var user = firebase.auth().currentUser;
console.log(user);
var uid;
if (user != null) {
uid = user.uid;
console.log(uid)
var firebaseRef = firebase.database().ref();
var userData = {
userArtistName: userArtistName,
userEmail: userEmail,
userIsArtist: true,
userId: uid,
}
firebaseRef.child('users/' + uid).set(userData).then(() => {
window.location.replace('main.html');
}).catch();
console.log('User successfully created!' + 'logged in as:' + userEmail);
}})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
There where alot of issues with the redirect actually, so now I placed the replace itself in the promise of the firebaseRef.child and not the createUserWithEmailAndPassword . This made it work!

Categories