1 回答
TA贡献1824条经验 获得超6个赞
我假设您的用户模型具有用户名和密码字段,并且您的密码在 db 中加密。
对于使用 username 查找用户,如果用户发现将 user.password 与请求正文中的加密密码进行比较。如果未找到用户或密码不匹配,我将发送400-Bad Request.
const bcrypt = require("bcryptjs");
router.post("/", async (req, res) => {
const { username, password } = req.body;
if (!(username && password))
return res.status(400).json({ error: "username and password are required" });
try {
let user = await User.findOne({ username });
if (!user) return res.status(400).json({ error: "invalid login" });
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) return res.status(400).json({ error: "invalid login" });
user.password = undefined;
res.json(user);
} catch (err) {
console.log(err);
return next(err);
}
});
要在保存用户之前对密码进行哈希处理,您可以将此代码添加到用户模型中吗?
UserSchema.pre('save', async function (next) {
this.password = await bcrypt.hash(this.password, 12);
next();
});
报名路线:
router.post("/register", async (req, res) => {
const { username, password } = req.body;
if (!username || !password)
return res.json({ success: false, msg: "Please pass username and password." });
try {
let user = await User.findOne({ username });
if (user) return res.json({ success: false, msg: "Username already exists." });
user = new User({ username, password });
await user.save();
res.json({ success: true, msg: "Successful created new user." });
} catch (err) {
console.log(err);
res.json({ success: false, msg: "Something went bad" });
}
});
添加回答
举报