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.
Related
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.
I'm trying to print firebase display name.
its showing after login. but after registrtion its showing null value. I'm using react-firebase-hook
const [userAuthenticate,loadingAuthenticate] = useAuthState(auth)
const [update,setUpdate] = useState(auth)
useEffect(()=>{
const tokenUpdate = async()=>{
if(userAuthenticate && update){
console.log(userAuthenticate.displayName); // Showing Null
navigate('/');
}
}
tokenUpdate();
},[userAuthenticate,update]);
const onSubmit = async(data) => {
const name = data.name;
const email = data.email;
const password = data.password;
await createUserWithEmailAndPassword(email, password);
await updateProfile({ displayName: name });
await sendEmailVerification(email)
setUpdate(true);
};
Updating the profile does not automatically refresh the profile in the current application. You'll need to reload the user's profile after the call to updateProfile completes.
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.
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());
});
});
}
});
}
This may seem like an obvious question, but i'm having trouble creating a user inside of my Firebase db. I'm very new to firebase and coding for that matter.
How I understand it to be is when a user clicks the sign up button, a user with the newly authenticated uid will be created under 'object/users". However the user is always null. In the google documentation it says that sometimes the user is null because it hasn't finished initializing the user. And to put it inside of onAuthStateChanged. This works, however, if I did this a user would be created/overwritten every time they log in or log out.
I suppose what I'm looking for is some solution to create a user inside of my firebase db when a user first signs up with valid information.
Here is my code:
function LoginCtrl($scope) {
$scope.txtEmail = document.getElementById('txtEmail');
$scope.txtPassword = document.getElementById('txtPassword');
$scope.btnLogin = document.getElementById('btnLogin');
$scope.btnSignUp = document.getElementById('btnSignUp');
$scope.btnLogout = document.getElementById('btnLogout');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
createUser();
});
function createUser() {
var user = firebase.auth().currentUser;
if (user != null) {
const dbRefObject = firebase.database().ref().child('object');
const dbRefList = dbRefObject.child("users/" + user.uid);
dbRefList.set({
name: "jim",
});
}
}
btnLogout.addEventListener('click', e => {
firebase.auth().signOut();
});
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser);
btnLogout.classList.remove('hide');
btnLogin.classList.add('hide');
} else {
console.log('not logged in');
btnLogout.classList.add('hide');
btnLogin.classList.remove('hide');
}
})
}
The culprit is in these three lines:
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
createUser();
You are firing off createUser() too soon. In the above code fragment, this happens right after starting the (asynchronous) registration process – the SDK never had a chance to actually create the user in the auth database!
The createUserWithEmailAndPassword returns a promise, as reflected in your local variable. What you need to do here is chaining the two calls, i.e. start the database manipulation after the promise is fulfilled.
Try this:
// inside the click handler
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
auth.createUserWithEmailAndPassword(email, pass)
.then(user => createUser(user)) // <-- important!
.catch(e => console.log(e.message));
});
function createUser(user) {
// no need for currentUser if you pass it in as an argument
if (user) {
...
}
}