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);
}
}
Related
I'm trying to let the user sign in using either email or username, I'm trying this code in Postman and each time I try it gives me this error:
"success":false,"status":500,"message":"data and hash arguments
required","stack":"Error: data and hash arguments required\n at
Object.compare
Auth.js Configurations:
const emailRegex = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/";
router.post("/login", async (req, res, next) => {
const isEmail = String(req.body.emailOrUsername).match(emailRegex);
try {
if (!req.body.password) {
return next(createError(400, "Invalid password"));
}
let user;
if (isEmail) {
user = await User.findOne({ where: { email: req.body.emailOrUsername } });
} else {
user = await User.findOne({ where: { username: req.body.emailOrUsername } });
};
if (!user) return next(createError(404, "User not found!"));
const isPasswordCorrect = await bcrypt.compare(
req.body.password,
user.password
);
if (!isPasswordCorrect) return next(createError(400, "Wrong password!"));
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
next(err);
}
});
I'm not sure what I'm missing here!
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 ?
I need to hash the password before insert in the DB I have the function of bcrypt but I don't know how to get it into a const and use it for make the insert into mysql.
I'm using bcrypt for it, so what's the method I should follow to get the password hashed?
async postCompletedetails(req, res) {
const company = req.params.company;
const name = req.params.name;
const password = req.params.password;
bcrypt.hash(password, saltRounds, (err, hash) => {
});
if (
company !== undefined &&
name !== undefined &&
password !== undefined
) {
const { token } = req.headers;
const decoded = jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION);
const id = decoded.id;
const update = await pool.query(
`UPDATE user SET Name_user= '${name}', password= '${password}' WHERE ID_user = ${id}`
);
const incompany = await pool.query(
`INSERT INTO company (Name_company) VALUES ('${company}') `
);
const inrelcompany = await pool.query(
`INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), ${id})`
);
return res.json({
code: 200,
message: "todo bien... todo correcto y yo que me alegro",
password,
});
} else {
return res.json({
code: 400,
message: "Bro hiciste algo mal",
});
}
}
async postCompletedetails(req, res) {
const company = req.params.company;
const name = req.params.name;
const password = req.params.password;
const saltRounds = 10;
if (
company !== undefined &&
name !== undefined &&
password !== undefined
) {
const hashPass = bcrypt.hash(password, saltRounds, (err, hash) => {
if (err)
{
return err;
}
return hash;
});
hashPass // this will be what you insert into the database.
}
Ok, I have it but the problem is that I can't get the hashed password, hassPass have de value undefined, what I should change?
const hashPass = await bcrypt.genSalt(saltRounds, function (err, salt) {
if (err) {
throw err
} else {
bcrypt.hash(password, salt, function(err, hash) {
if (err) {
throw err
} else {
console.log(hash)
}
})
}
})
The password is being hashed, I now it for the console.log
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!
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.