post error firebase authentication with react js - javascript

i am encountering a problem concerning firebase authentication
so whenever I submit the form the state will get the signup data but it will not send it to my firebase database
utils.js
export const handleUserProfile = async({ userAuth, additionalData }) => {
if (!userAuth) return;
const { uid } = userAuth;
const userRef = firestore.doc(`users/${uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { displayName, email } = userAuth;
const timestamp = new Date();
const userRoles = ['user'];
try {
await userRef.set({
displayName,
email,
createdDate: timestamp,
userRoles,
...additionalData
});
} catch (err) {
console.log(err);
}
}
return userRef;
};
in Signup.js :
handleSubmit = async event => {
event.preventDefault();
const { displayName, email, password, confirmPassword } = this.state;
if (password !== confirmPassword) {
const err = ['Password Don\'t match'];
this.setState({ errors: err })
return
}
try {
const { user } = await auth.createUserWithEmailAndPassword(email, password);
await handleUserProfile(user, { displayName })
this.setState({
...initialState
})
}
catch (err) {
}
}
where i am missing ?

Related

How to prevent this error from happening? (NODEJS Bcryptjs)

I created a user update controller in my application, but the problem is that when testing this in postman, I can't just send information that I want to edit without having to pass the password along, which is being rendered asynchronously with the bcryptjs
error:
Error: Illegal arguments: undefined, string
at Object.bcrypt.hashSync (/home/pc/api_foodelivery/node_modules/bcryptjs/dist/bcrypt.js:189:19)
at exports.update (/home/pc/api_foodelivery/src/controllers/UserController/UpdateUser.js:16:37)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
const db = require('../../models/index');
const bcrypt = require('bcryptjs');
exports.update = async (req, res) => {
const { id } = req.params;
const { firstName, lastName, email, password, phoneNumber } = req.body;
try {
const user = await db.User.findOne({ where: { id } });
if (!user) {
return res.status(401).json('User does not exist');
}
const hashPassword = bcrypt.hashSync(password, 8);
await user.update({
firstName,
lastName,
email,
password: hashPassword,
phoneNumber,
});
return res.status(200).json('User updated!');
} catch (err) {
return console.log(err);
}
}
From what I understand, this error occurs because I am not passing anything to my hashPassword, but how can I make this not mandatory when updating my database user?
const db = require('../../models/index');
const bcrypt = require('bcryptjs');
exports.update = async (req, res) => {
const { id } = req.params;
const { firstName, lastName, email, password, phoneNumber } = req.body;
try {
const user = await db.User.findOne({ where: { id } });
if (!user) {
return res.status(401).json('User does not exist');
}
// You need to check here if user wants to update password or not
const updatedUser = {
firstName,
lastName,
email,
phoneNumber
} // You may further check for every filed if not undefined here
if(password && password !== "") {
const hashPassword = bcrypt.hashSync(password, 8);
updatedUser.password = hashPassword
}
await user.update(updatedUser);
return res.status(200).json('User updated!');
} catch (err) {
return console.log(err);
}
}

my homepage wont render using my google oauth

This is the error that I get:
"You have created a new client application that use…i/web/guides/gis-migration) for more information."
here are my codes on server, the statement inside console.log doesnt even show:
static async googleLogin(req, res, next) {
try {
console.log("masuk google login server")
const { id_token } = req.body
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)
const ticket = await client.verifyIdToken({
idToken: id_token,
audience: process.env.GOOGLE_CLIENT_ID
});
const payload = ticket.getPayload()
const email = payload.email
let password = email.toString().split('#')
password = password[0]
let user = await User.findOne({ where: { email } })
if (!user) {
let newUser = { email, password }
let createUser = await User.create(newUser)
const payload = {
id: createUser.id,
email: createUser.email
}
const access_token = generateToken(payload)
return res.status(201).json({ access_token })
} else {
const payload = {
id: user.id,
email: user.email
}
const access_token = generateToken(payload)
return res.status(200).json({ access_token })
}
} catch (err) {
console.log(err)
return next(err)
}
}
the console.log in my client also doesnt show
function onSignIn(googleUser) {
console.log("masuk client oauth")
$.ajax({
method: "POST",
url: `${baseUrl}/users/google-login`,
data: {
id_token: googleUser.getAuthResponse().id_token
}
})
.done((response) => {
console.log(response, "client response")
localStorage.setItem("access_token", response.access_token)
checkLocalStorage();
})
.fail((err) => {
console.log(err, "error client");
})
.always(() => {
authentication()
})
}
i tried deleting cache and run my app again, recreate a new project on google api (which genereated new ID). they didnt work

want to create a subcollection in document in firebase when user sign up to app in react native its children subcollection created

want to add a subcollection when the user signs up to the app a subcollection is created to its document which contains its children.
here is my code:
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
const currentUser = firebase.auth().currentUser;
const db = firebase.firestore();
db.collection("users")
.doc(currentUser.uid)
.set({
email: currentUser.email,
lastName: lastName,
firstName: firstName,
}).collection('users').doc(currentUser.uid).collection("recipient").add({name:"test", age:"25" }).then((data) => {
console.log(data.id);
console.log("Document has added")
}).catch((err) => {
console.log(err)
})
} catch (err) {
alert("There is something wrong!!!!" + err.message.toString());
}
}
The problem in your code is linked second add document to sub-collection because the first promise does not return the document reference but a sort of information about how long operation was taken. The right approach will be the following:
async function addUser(id, user) {
const db = firebase.firestore();
const users = db.collection('users')
try {
const result = await users.doc(id).set(user)
return result
} catch (e) {
console.log("addUser: ", e)
return null
}
}
async function getUserRef(id) {
const db = firebase.firestore();
const users = db.collection('users')
try {
const docSnapshot = await users.doc(id).get()
return docSnapshot.ref
} catch (e) {
console.log("getUserRef: ", e)
return null
}
}
try {
const user = {
email: currentUser.email,
lastName: lastName,
firstName: firstName,
}
const result = await addUser(id, user);
const ref = await getUserRef(id)
await ref.collection("recipient").add({name:"test", age:"25" })
} catch (e) {
console.log(e)
}

Firebase emailVerified variable isn't changing after clicking the confirmation email

I am using firebase with ReactJS, after creating a user I am sending a confirmation email, after clicking the link, the variable emailVerified remains false no matter what I try.
Here's the code where I create the user and send the email:
const createUserWithEmailAndPasswordHandler = async (event, email, password) => {
event.preventDefault();
try{
const {user} = await auth.createUserWithEmailAndPassword(email, password);
user.sendEmailVerification().then(function() {
user.reload()
}).catch(function(error) {
console.log(error);
});
generateUserDocument(user, {displayName});
}
catch(error){
setError('Error Signing up with email and password');
}
}
And this is the generateDocument code:
export const generateUserDocument = async (user, additionalData) => {
if (!user) return;
const userRef = firestore.doc(`users/${user.uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { email,emailVerified, displayName, photoURL } = user;
try {
await userRef.set({
displayName,
email,
emailVerified,
photoURL,
...additionalData
});
} catch (error) {
console.error("Error creating user document", error);
}
}
return getUserDocument(user.uid);
};
Even if I logout and login, refresh the page, it still doesn't change to true.
Thanks for any help!

Getting error " Route.post() requires a callback function but got a [object Undefined]"

Can anyone explain to me why I'm getting this error? Here's my code where I'm getting this error. I assume it's becuase of the imports/exports in my code?
emailController
const User = require("../models/User")
const jwt = require("jsonwebtoken")
const { transporter, getResetPasswordURL, resetPasswordTemplate } = require("../utils/mailer")
module.exports = {
createOneTimeTokenAndSendMail: async (req, res) => {
const email = req.params.email
try {
const user = await User.findOne({ email })
if (!user) {
return res.status(404).json({ error: "No user with that email "})
}
const hashedPassword = user.password
const createdAt = user.createdAt
const userId = user._id
const secret = hashedPassword + "-" + createdAt
const token = jwt.sign({ userId }, secret, {
expiresIn: 3600
})
const url = getResetPasswordURL(user, token)
const emailTemplate = resetPasswordTemplate(user, url)
const sendEmail = () => {
transporter.sendMail(emailTemplate, (err, info) => {
if (err) {
res.status(500).json("Error sending email")
}
console.log("email sent", info.response)
})
}
sendEmail()
} catch (error) {
res.status(500).json({ error })
}
}
}
mailer
const User = require("../models/User")
const jwt = require("jsonwebtoken")
const {
transporter,
getResetPasswordURL,
resetPasswordTemplate
} = require("../utils/mailer")
module.exports = {
createOneTimeTokenAndSendMail: async (req, res) => {
const email = req.params.email
try {
const user = await User.findOne({ email })
if (!user) {
return res.status(404).json({ error: "No user with that email " })
}
const hashedPassword = user.getPassword
const createdAt = user.createdAt
const userId = user._id
const secret = hashedPassword + "-" + createdAt
const token = jwt.sign({ userId }, secret, {
expiresIn: 3600
})
const url = getResetPasswordURL(user, token)
const emailTemplate = resetPasswordTemplate(user, url)
const sendEmail = () => {
transporter.sendMail(emailTemplate, (err, info) => {
if (err) {
res.status(500).json("Error sending email")
}
console.log("email sent", info.response)
})
}
sendEmail()
} catch (error) {
res.status(500).json({ error })
}
}
}
This is the route which is throwing the above error:
router.post("/reset-password/:email", emailController.createOneTimeTokenAndSendMail)
I have been dealing with errors like these constantly, so I'd like to clear my doubts once and for all.

Categories