Firebase - email is not defined - javascript

I am trying to build a function that allows user to change their password. The problem is when I am getting the current user's data it shows that the email is null.
Everything works on Firebase, users are creating in Firebase auth system.
Here is a part of my code
reauthenticate = (currentPassword) => {
var user = firebase.auth().currentuser;
var cred = firebase.auth.EmailAuthProvider.credential(user.email, currentPassword);
user.reauthenticateWithCredential(cred);
}
reauthenticate(currentPassword).then(() => {
var user = firebase.auth().currentuser;
user.updatePassword(newPassword).then(() => {
alert("Password changed");
window.location.replace("./index.html");
}).catch((error) => {
console.log(error);
})
});
What console shows is Uncaught TypeError: Cannot read properties of undefined (reading 'email') at reauthenticate (password.js:15:64) at changePassword (password.js:27:9)

its currentUser not currentuser. Capital U.
const user = firebase.auth().currentUser;

Related

"Cannot read properties of undefined (reading 'params')"

I'm trying after successful login, to redirect the user on another page.
I'm on Svelte JS, and i use Routify, Firebase for Auth and datas
my imports :
import { Router, redirect, routes, goto } from "#roxi/routify";
my function to verify form and redirect when user is ok
// submit form
let params = {};
function handleSubmission({params}) {
hasBeenClicked = true;
if (isValidEmail && isValidPassword) {
// Trim email and password
let trimEmail = email.trim();
let trimPassword = password.trim();
// Initialize Firebase
const auth = getAuth();
const db = getFirestore();
// Test connection
signInWithEmailAndPassword(auth, trimEmail, trimPassword)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log('user',user.uid);
// Try to redirect to the page with the params
// doc : src/pages/admin/[business].svelte corresponds to /admin/:business, where :business // is a parameter.
$goto(`/adminUser/userPage:params?user=${user.uid}`, params);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode, errorMessage);
});
}
}
when i submit i got this :
Cannot read properties of undefined (reading 'params')
I've been read the doc, but I can't figure out what to do and how to put the user in the params.

Firebase web realtime database stiring user id as undefined

I have a create user and login authentication setup with firebase realtime database. I have a user field in my database where I will store user data. However, I would like to create a child element under the user field that is the user id then the user information can be displayed under that child.
So far I have tried to create such a field with this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getDatabase, set, ref, update } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
//Signup section
signup.addEventListener('click',(e) => {
var username = document.getElementById('signup-user').value;
var email = document.getElementById('signup-email').value;
var schoolID = document.getElementById('signup-id').value;
var password = document.getElementById('signup-pwd').value;
createUserWithEmailAndPassword(auth, email, password, schoolID)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
update(ref(database, "user/" +user.id),{
username: username,
schoolID: schoolID,
email: email
})
alert('User Created!');
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert('Error please try again');
// ..
});
});
But it only gives me an undefined field in my realtime database:
Not only that but it overwrites the previous entry every time a make an new user.
userCredential.user is a User type object, which is a subclass of UserInfo. As you can see from the linked API documentation, User doesn't have an property called id. It will always be undefined.
What you want instead is uid.
update(ref(database, "user/" + user.uid), {...})

Firebase .getIdToken() returns invalid token

I'm trying to make just a simple authentication app with electron and firebase redirect, but if the user is already logged in and I use the firebase.auth().currentUser.getIdToken() to get the IdToken of that user, but when i try that token in
firebase.auth().signInWithCredential(credential) I get the error that says ERROR: auth/invalid-credential
Here is my code front-end
firebase.auth().onAuthStateChanged( async function (user) {
if (user) {
// User is signed in.
var user = await firebase.auth().currentUser;
if (user != null) {
await firebase.auth().currentUser.getIdToken().then(function(idToken) {
window.location.href = "electron://"+idToken;
}).catch(function(error) {
console.log(error)
});
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
Here is my code back-end
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (commandLine[2]) {
var url = commandLine[2].split('/')
var id_token = url[2]
console.log('id: ', id_token)
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential)
.then((success)=>{
myWindow.loadFile('./scr/welcome.html')
console.log('RESULT: ',success)
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('ERROR:', errorMessage)
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.log('ERROR:', credential)
// ...
})
}
I'm missing something or doing something wrong?
That's not how ID tokens work. The purpose of an ID token is to pass to your backend, so that it can validate the identity of the signed in user, and perform some action on their behalf. It's not valid for signing in on the client again. You might want to review the documentation on use of ID tokens to learn how this works.
signInWithCredential only works with Google Auth when you correctly construct a GoogleAuthProvider credential. There is plenty of sample code in the API documentation for that.

deleting user, problems with reauthenticating firebase

Hello I'm trying to reauthenticate the user before they delete their account but I'm having one problem I can't seem to solve; how do I obtain the user's password if I didn't save it since that would be a privacy issue. I've seen other posts about this but they don't mention how they got the password. This is my code for deleting account:
const onDeleteAccountPress = () => {
firebase.database().ref('users/'+userId).remove()
var userReauth = firebase.auth().currentUser
const credential = firebase.auth.EmailAuthProvider.credential(userReauth.email,userProvidedPassword)
userReauth.reauthenticateWithCredential(credential)
for(let i =0; i < goalCounter; i++){
firebase.database().ref('goals/'+(courseGoals[i].id)).remove()
}
userReauth.delete()
.then(function(){
props.navigation.navigate('Login');
props.navigation.reset({ index: 0, routes: [ { name: 'Login' } ] });
}).catch(function(error){
console.log(error)
console.log('there is something wrong')
})
}
When the user logs in, you can store the password inside localStorage, then if the user wants to delete the account, you can get the password from the storage and pass it to the EmailAuthProvider.credential() method.

How to convert an anonymous account to a permanent account

can someone help me how to convert an anonymous account (signInAnonymouslyAndRetrieveData) to a permanent account ?
I have tried this:
firebase.auth().currentUser.linkAndRetrieveDataWithCredential(credential).then(function(usercred) {
var user = usercred.user;
console.log("Anonymous account successfully upgraded", user);
}, function(error) {
console.log("Error upgrading anonymous account", error);
});
but i'm getting an
cannot read property "linkAndRetrieveDataWithCredential" of null
error.
firebase.auth().currentUser will be null if there's no currently signed in user.
Ensure your anonymous user is still signed in then as in your example above you can then upgrade your user using linkAndRetrieveDataWithCredential
const credential = firebase.auth.EmailAuthProvider.credential(email, password);
const currentUser = firebase.auth().currentUser;
if (currentUser) {
currentUser.linkAndRetrieveDataWithCredential(credential).then((userCredential) => {
const user = userCredential.user;
console.log("Account linking success", user);
}, (error) => {
console.log("Account linking error", error);
});
}
References:
Official Firebase guide to account linking:
https://firebase.google.com/docs/auth/web/account-linking
React Native Firebase reference doc:
https://rnfirebase.io/docs/v4.3.x/auth/reference/User#linkAndRetrieveDataWithCredential

Categories