我正确地将mongoose.encryption设置为我的代码。我知道,因为当我进入“ /注册”路由时,我的密码已正确加密。
app.get('/cadastrar', (req, res) => {
res.render('registrar');
});
app.post('/cadastrar', (req, res) =>{
const cadastro = req.body.cadastro;
User.create({nickname: cadastro.nickname, email: cadastro.email, password: cadastro.password},(err) => {
err ? console.log(err) : console.log('Successfully added a new user!'); res.render('/');
});
})
注册后在我的密码下面:
{
"_id" : ObjectId("5cbb2dce3014e52b34732df8"),
"nickname" : "Bulbassauro",
"email" : "bulba@pokemon.com",
"_ct" : { "$binary" : "YeLrW1jgdaT4IBFaBExr+Y4IUVkA5UtJoww6hYKqynAVg7OYjEuhJhQt2z2CtIBPHQ==", "$type" : "00" },
"_ac" : { "$binary" : "YUmRsA2QBkUw9fgyNTimqAeEPxsLgjtI4bLErh2FJmZCWyJfaWQiLCJfY3QiXQ==", "$type" : "00" },
"__v" : 0
}
我重构了代码,所以我有一个不同的文件来设置我的mongoose.Schema:
const mongoose = require('mongoose');
const encrypt = require('mongoose-encryption');
const userSchema = new mongoose.Schema(
{
nickname : String,
email : String,
password : String
}
);
const secret = 'viciadoemjogo';
userSchema.plugin(encrypt, {secret: secret, encryptedFields:['password']});
module.exports = mongoose.model('User', userSchema);
以下是我的登录路线。但是我无法登录。这意味着我的密码未被解密。 那就是我收到错误消息:缺少身份验证代码
app.get('/login', (req, res) => {
res.render('registrar');
});
app.post('/login', (req, res) => {
const email = req.body.login.email;
const password = req.body.login.password;
User.findOne({email: email}, (err, foundUser) =>{
if(err){
console.log(err);
} else {
if(foundUser){
if(foundUser.password === password){
res.render('nivelamento');
}
}
}
});
});
谁能告诉我为什么我不能登录?
答案 0 :(得分:0)
错误来自 const email = req.body.login.email; const 密码 = req.body.login.password;
应该是 const email = req.body.email; const 密码 = req.body.password;
一旦您将代码更新为此更改,一切都会正常进行。猫鼬加密的工作原理是,当您 save() 加密时,当您调用 find() 或 findOne() 时,它将解密。所以你是在比较 pass-string 和 pass-string 而不是 pass-hash。