Firebase: Error (auth/user-token-expired) - javascript

let me first note that I am new to firebase and authentication matters ... for several days I am facing a problem with updating email and password functionality using firebase... I want to know if this problem have something with using React and its way of working like re-rendering components ..etc. or is it the use of promises the way i've done in the code below.. I really don't know.
This is the error that I am facing.
Uncaught (in promise) FirebaseError: Firebase: Error (auth/user-token-expired).
Here is the code involved in the situation
firebase.js
const updateUserEmail = (newEmail) => {
return updateEmail(auth.currentUser, newEmail);
}
const updateUserPassword = (newPassword) => {
return updatePassword(auth.currentUser, newPassword);
}
update_profile.jsx
async function handleUpdateProfile() {
setErrorMessage('');
setIsLoading(true);
// check for password equality
if (passwordInputRef.current.value !== confirmPasswordInputRef.current.value) {
setErrorMessage('Passwords do not match');
return;
}
const promises = [];
if (emailInputRef.current.value !== currentUser?.email) {
promises.push(updateUserEmail(emailInputRef.current.value));
}
if (passwordInputRef) {
promises.push(updateUserPassword(passwordInputRef.current.value);
}
Promise.all(promises).then(() => {
navigate('/');
}).catch((err) => {
console.log(currentUser);
console.log(err)
setErrorMessage('Couldn\'t Update Your Profile');
}).finally(() => {
setIsLoading(false);
})
}
I tried auth.currentUser.reload()
like that
auth.currentUser.reload().then(() => {
updateEmail(auth.currentUser, newEmail);
})
I tried Re-authenticate the user using the doc guide here
firebaseDocs
but nothing solved the error.

Finally I have come to an answer for my question that has worked
I am not quite sure, but I believe that the root of my problem returns to two things
Reauthentication of a user
Async matters
Here is how I solved the error
firebase.js
const updateUserEmail = async (newEmail) => {
const email = prompt('Please Enter Your Email');
const password = prompt('Please enter your password');
let credential = EmailAuthProvider.credential(email, password);
await reauthenticateWithCredential(auth.currentUser, credential).then(() => {
updateEmail(auth.currentUser, newEmail);
})
}
const updateUserPassword = async (newPassword) => {
const email = prompt('Please Enter Your Email');
const password = prompt('Please enter your password');
let credential = EmailAuthProvider.credential(email, password);
await reauthenticateWithCredential(auth.currentUser, credential).then(() => {
updatePassword(auth.currentUser, newPassword);
})
}
for each update I prompted the user to give me his email and pass, and then used it for reauthenticating matters.
to fix the async issue.. i made the function to wait for the first update (email) before proceeding to the next update (password) and the next lines of code clarify it more.
update_profile.jsx
let newEmail = false;
let newPassword = false;
if (emailInputRef.current.value !== currentUser?.email) {
newEmail = true;
}
if (passwordInputRef) {
newPassword = true;
}
if (newEmail) {
await updateUserEmail(emailInputRef.current.value);
if (newPassword) {
await updateUserPassword(passwordInputRef.current.value);
}
}
I bet there are better solutions than mine and I'll be happy to read it, but for now this will do the trick.

Related

Uncaught Error in snapshot listener:, FirebaseError: [code=permission-denied]: Missing or insufficient permissions

I am trying to let the user only read and write their own data. My rules are as follow(from the docs)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
}
}
The uid for my user matches my document id but i still get the error:
Uncaught Error in snapshot listener:
FirebaseError: [code=permission-denied]: Missing or
insufficient permissions.
My code for getting uid to document id
const handleSignUp = async () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(async (UserCredentials) => {
const user = UserCredentials.user;
console.log("Registered with: ", user.email);
try {
const uidRef = doc(db, 'users', user.uid);
const docRef = await setDoc(uidRef, {
name: name,
age: age,
currentWeight: currentWeight,
goalWeight: goalWeight,
});
} catch (e) {
console.error("Error adding document: ", e);
}
I am really lost as I have tried many different ways and all docs / answers on here do not work for me. I am guessing the error comes when i call snapshot in this code
const getUser = async() => {
const subscriber = onSnapshot(usersRef, (snapshot) => {
let user = []
snapshot.docs.forEach((doc) => {
user.push({...doc.data(), key: doc.id })
})
setUser(user);
console.log(user);
})
return () => subscriber();
};
I am just unsure as to what is exactly wrong here. Is it my rules? My snapshot?
Given that you get a QuerySnapshot result, I suspect that your code is reading the entire users collection. But as the documentation says rules are not filters, but instead merely ensure that your code only tries to access data that it is permitted to.
So your code should only try to read the document of the currently signed in user.
const getUser = async() => {
if (getAuth().currentUser) {
const uidRef = doc(db, 'users', getAuth().currentUser.uid);
const subscriber = onSnapshot(uidRef, (doc) => {
setUser({...doc.data(), key: doc.id })
})
...
}
};

Error: Firebase reCAPTCHA placeholder element must be empty

I am using firebase authentication with phone number, and that requires Recaptcha verification. I had initially used the normal visible recaptcha, and that worked fine, but a need came in to make the recaptcha an invisible one.
I used Firebase's documentations on this and here's my code below:
const generateRecaptcha = () => {
window.recaptchaVerifier = new RecaptchaVerifier(
"signin_btn",
{
size: "invisible",
callback: (response) => {
onSignInSubmit();
},
},
auth
);
};
const onSignInSubmit = async () => {
setLoading(true);
const q = query(doc(db, "users", phone));
const querySnapshot = await getDoc(q);
console.log("Snapshot", querySnapshot.exists());
if (
phone === "" ||
password === "" ||
repeatPassword === "" ||
lastname === "" ||
firstname === ""
) {
setLoading(false);
setErrors("Please fill the needed fields.");
} else if (password !== repeatPassword) {
setErrors("Passwords do not match.");
setLoading(false);
} else if (querySnapshot.exists()) {
setErrors(
"This phone number already exists on the server. Please try another number."
);
setLoading(false);
} else {
setErrors("Complete ReCaptcha to get verification code");
generateRecaptcha();
let appVerifier = window.recaptchaVerifier;
console.log("Did we get here?");
signInWithPhoneNumber(auth, phone, appVerifier)
.then((confirmationResult) => {
console.log("We got here..!!");
window.confirmationResult = confirmationResult;
setLoading(false);
})
.catch((err) => {
console.error(err);
});
}
};
I end up getting this error though
Please I need help on this issue.

How to reauthorize a user in Firebase?

Environment
Firebase JavaScript SDK v8
Question
How can I re-authorize an already-logged-in user with their password? What I want to do is like below:
const password = "some-password"
firebase.reAuthorizeUser(password)
.then(() => console.log("ok"))
.catch(() => console.log("ng"))
Thank you in advance.
You are looking for reauthenticateWithCredential method.
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 ocurred
// ...
});
Checkout reauthenticate a user in the documentation.
You can do a switch case based on providerId, below should help.
user.providerData.forEach((profile) => {
switch (profile.providerId) {
case 'google.com':
user
.reauthenticateWithPopup(new firebase.auth.GoogleAuthProvider())
.then((UserCredential) => {
**//reauthenticated successfully!**
})
})
.catch((error) => {
**//Something is wrong**
})
break
case 'password':
// eslint-disable-next-line no-case-declarations
const credentials = firebase.auth.EmailAuthProvider.credential(
user.email,
userPassword
)
user
.reauthenticateWithCredential(credentials)
.then(() => {
**//reauthenticated successfully!**
},
})
})
.catch(() => {
**//Something is wrong**
})
break
})
SDK v9
import {getAuth, reauthenticateWithCredential, EmailAuthProvider} from "firebase/auth";
const reauthenticate = async () => {
try {
const auth = getAuth();
const user = auth.currentUser;
const credential = await EmailAuthProvider.credential(
email,
password
);
await reauthenticateWithCredential(user, credential);
return true
} catch (e) {
return null
}
}
const credential = promptForCredentials();
this is giving me error
cant find variable: promptForCredentials.

Correct way to pass async eerror

I have a function which uses Firebase auth to update a user's email:
export const updateEmail = async (email) => {
const user = auth.currentUser;
return user.updateEmail(email);
};
It is used in a function which gets an email from a form (in React) and tries to update the email. If there is an error, we change the state to reflect that.
handleSave = (e) => {
const email = e.target.email.value;
updateEmail(email).catch((err) => {
this.setState({ didError: true, emailError: err.message });
});
};
However, when an error occurs, in the console I get:
My question is: why does this still say 'Uncaught'? Does the .catch() in handleSave not take care of that?
update
Link to relevant Firebase docs
Assuming updateEmail returns a prmise, I guess you can try:
export const updateEmail = (email) => { // no need for async here
const user = auth.currentUser;
return user.updateEmail(email);
};
handleSave = async (e) => {
const email = e.target.email.value;
try{
await updateEmail(email);
}catch(err){
this.setState({ didError: true, emailError: err.message });
}
};
I'm not quite sure since I don't know so much about Firebase, let me suggest something.
export const updateEmail = async (email) => {
const user = auth.currentUser;
const response = await user.updateEmail(email);
if ( response.error ) {
throw new Error( response.error );
}
return "something else";
};

How do I add a user to my Firebase DB with it's unique id when I first create a user for authentication

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) {
...
}
}

Categories