I am stuck here figuring out why the password argument from bcrypt.comapare(password, user.password)
line keeps getting value from const {password, ...rest} = user;
instead of const {email, password} = req.body
line.
I know that I can fix this issue by changing variables' name, but I'm curious about the reason why...
For me it doesn't make sense that it is referring to the variable that is not even declared.
Thanks!
util.js
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
// Create a token for logged in user
export const createToken = (user) => {
if (!user.role) {
throw new Error("No user role specified");
}
return jwt.sign(
{
sub: user._id,
email: user.email,
role: user.role,
iss: "my-api",
aud: "my-api",
},
"asldkfjaslasfdasdfasdfsadfasfdsfdsf",
{ algorithm: "HS256", expiresIn: "1h" }
);
};
// Verify password
export const verifyPassword = (passwordAttempt, hashedPassword) => {
return bcrypt.compare(passwordAttempt, hashedPassword);
};
userController.js
import User from "../models/User";
import jwtDecode from "jwt-decode";
import bcrypt from "bcryptjs";
import { createToken, verifyPassword } from "../util";
export const userAuthenticate = async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({
email,
}).lean();
if (!user) {
return res.status(400).json({ Error: "No user found" });
}
const match = await bcrypt.compare(password, user.password);
if (!match) {
return res.status(400).send("No user found");
}
const token = await createToken(user);
const { password, ...rest } = user;
const userInfo = Object.assign({}, { ...rest });
const decodedToken = jwtDecode(token);
console.log(decodedToken);
return res.status(200).json({
//userInfo,
});
} catch (error) {
console.log(error);
return res.status(400).send(error);
}
};