I’m learning Crypto.JS and Node.JS, and am currently struggling with a Malformed UTF-8 data
error when accessing the login endpoint with Postman. I know that the login credentials are correct, but when I send the POST request to the endpoint, it throws me with that error. Is there a simple fix for this?
const router = require('express').Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.SECRET_PASSPHRASE).toString()
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username })
!user && res.status(401).json("Invalid username or password");
const hashedPassword = CryptoJS.AES.decrypt(user.password, process.env.SECRET_PASSPHRASE);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
originalPassword !== req.body.password && res.status(401).json("Invalid username or password");
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin
},
process.env.ACCESS_TOKEN_SECRET,
{expiresIn: "3d"}
);
const { password, ...others } = user._doc;
res.status(200).json(others, accessToken);
} catch(err) {
console.log(err);
res.status(500).json(err);
}
});
module.exports = router;