Firebase v9: Firebase is not updating the user password - javascript

I'm using firebase version 9 and react. I'm trying to update the password of the user. The code for doing that is as follows:
await reauthenticateWithCredential(auth.currentUser, credentials)
.then(async () => {
console.log(password, auth.currentUser);
await updatePassword(auth.currentUser as any, password.trim())
.then(() => {
console.log("Password upd");
// await signOut(auth).finally(() => navigate("/"));
})
.catch((error) => {
console.log(error);
this.setState((state) => ({
...state,
error: {
field: "confirmPassword",
value: error.message,
},
}));
return;
});
})
I'm not getting any error and the i can be able to see in the console logs the message "Password upd" but the password is not updating for some reason. What maybe possibly the problem here?

Related

React JS || When the email already exists Firebase give me this Error: (auth/missing-email)

Please help me, I entered this code below but It doesn't work. When I give the correct email and password I get the error message ->
Here is my code:
const loginUser = (email, password, location, history) => {
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then(() => {
const destination = location?.state?.from || "/";
history.replace(destination);
setError("");
})
.catch((error) => {
setError(error.message);
})
.finally(() => setIsLoading(false));
};

Getting "TypeError: user.getIdToken is not a function" when updating password in firebase

When I run the function updatePassword I get the error "TypeError: user.getIdToken is not a function", which comes from a file in the firebase sdk.
async changePassword(state, payload) {
const user = auth.currentUser
let cred = EmailAuthProvider.credential(
payload.email,
payload.oldPassword
)
reauthenticateWithCredential(user, cred)
.then(() => {
// User re-authenticated.
console.log(payload.newPassword)
updatePassword(payload.email, payload.newPassword)
.then(() => {
// Update successful.
console.log('Succeed')
})
.catch((error) => {
console.log('Failed', error)
// An error ocurred
// ...
})
})
.catch((error) => {
// An error ocurred
// ...
console.log(error)
})
},
The updatePassword() function takes User as first parameter and not user's email. Try refactoring the code as shown below:
reauthenticateWithCredential(user, cred).then(({ user }) => {
// Pass user here and not payload.email
updatePassword(user, payload.newPassword).then(() => {
console.log('Succeed')
})
})

Is there a way to access my response error message?

Ok So i am trying to display my backend error messages in the front end, so I have it setup to send the response with the error code and a message and then in my action I am setting a state in my React component which I will then use to display the error message, so far I can get to display the error code but that is no use to most users so I would like to access the message I send with the code! So I want it to say user already exists or passwords do not match rather than Error: Request failed with status code 400
my action
export const signup = (form, router, setError) => async (dispatch) => {
const changeError = (error) => {
setError(error);
};
try {
const { data } = await api.signup(form);
dispatch({ type: AUTH, data });
router.push("/");
} catch (error) {
console.log(error);
changeError(error);
}
};
my node signup
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await user.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "User already exists." });
if (password != confirmPassword)
return res.status(400).json({ message: "Passwords do not match." });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await user.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
process.env.JWT_KEY,
{
expiresIn: "1h",
}
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong." });
}
};
After little search on Google, if you are using Axios as your api, the path to the error message is:
error.response.data.message
else, have you tried somthing like this?
error.data.message
or
error.message
as Guy said, slightly before I found the answer myself I set the error to error.response.data.message
so now I can set my error in the front end to display the message
and yea sorry was using axios, I'll know better for next time to mention that!
export const signup = (form, router, setError) => async (dispatch) => {
const changeError = (error) => {
setError(error);
};
try {
const { data } = await api.signup(form);
dispatch({ type: AUTH, data });
router.push("/");
} catch (error) {
console.log(error);
changeError(error.response.data.message);
}
};

Firebase email verification WITHOUT creating an account in React Native

I have question regarding email verification in Firebase. Solution to my problem I found here. But when I convert code to react native. It is not working as expected.
My function
const onSignIn = () => {
auth()
.signInAnonymously()
.then(() => {
console.log('User signed in anonymously');
auth()
.onAuthStateChanged((user) => {
user.updateEmail('jasurkurbanov96#gmail.com');
user.sendEmailVerification();
})
.catch(function (error) {
console.log('error', error);
});
})
.catch((error) => {
if (error.code === 'auth/operation-not-allowed') {
console.log('Enable anonymous in your firebase console.');
}
console.error(error);
});
navigation.push('SignUpConfirm');
};
Basically what I want to achieve is. When user enters to app, I need to show only email input. Once user
enters email address, Firebase should send confirmation code to the email user provided.
You should read the docs https://rnfirebase.io/reference/auth/user#updateEmail with the code below should works. if not print what error you got.
Sign In Screen
const onSignIn = () => {
auth()
.signInAnonymously()
.then(() => {
console.log('User signed in anonymously');
.catch((error) => {
if (error.code === 'auth/operation-not-allowed') {
console.log('Enable anonymous in your firebase console.');
}
console.error(error);
});
navigation.push('SignUpConfirm');
};
SignUpConfirm Screen
useEffect(() => {
auth().onAuthStateChanged((userIs) =>
userIs
.updateEmail('jasurkurbanov96#gmail.com')
.then(() =>
userIs
.sendEmailVerification()
.then(() => console.log('email verificiation sent')),
)
.catch((err) => console.log('This is', err)),
);
}, []);

Cannot read property 'navigate' of undefined in a .then() => { }

Why can't I navigate to the screen "App" in the following code. I get the error:
Cannot read property 'navigate' of undefined
async signIn() {
const { username, password } = this.state
await Auth.signIn(username, password)
.then(user => {
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
})
.catch(err => {
console.log('Error when signing in: ', err)
Alert.alert('Error when signing in: ', err)
})
}
}
You are mixing promises and await. You either await for the sign in, or remove the async/await and treat it like a promise. Also, it could be that you haven't binded the function so "this" points to undefined.
Either:
async signIn = () => {
const { username, password } = this.state
let user = await Auth.signIn(username, password);
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
}
}
Or
signIn = () => {
const { username, password } = this.state
Auth.signIn(username, password)
.then(user => {
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
})
.catch(err => {
console.log('Error when signing in: ', err)
Alert.alert('Error when signing in: ', err)
})
}
}

Categories