我已经为我的页面提供了 login/register
系统,但是我在尝试 login
时遇到了一个错误:
TypeError [ERR_INVALID_ARG_TYPE]: The "salt" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at check (internal/crypto/pbkdf2.js:59:10)
at Object.pbkdf2 (internal/crypto/pbkdf2.js:25:5)
at validPassword (/Users/krzysztofbialk/TO.DO/config/passwordUtils.js:14:29)
at /Users/krzysztofbialk/TO.DO/config/passport_log.js:21:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)
看来问题出在了这里:
passwordUtils.js
const crypto = require('crypto');
function genPassword(password) {
let salt = crypto.randomBytes(32).toString('hex');
let genHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
return {
salt: salt,
hash: genHash
};
};
function validPassword(password, hash, salt) {
let hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
return hash === hashVerify;
};
module.exports.validPassword = validPassword;
module.exports.genPassword = genPassword;
或 passport_log.js
const customFields = {
usernameField: 'email',
passwordField: 'password'
};
const verifyCallback = (username, password, done) => {
LogUser.findOne({username: username})
.then((user) => {
console.log(user)
if (!user) {return done(null, false)}
const isValid = validPassword(password, user.hash, user.salt);
if (isValid) {
return done(null, user);
} else {
return done(null, false);
}
})
.catch((err) => {
done(err);
});
};
// LOCAL STRATEGY; it looks good, doesn't it?
passport.use(new LocalStrategy(customFields, verifyCallback));
登录后路由
router.post('/login', passport.authenticate('local', { successRedirect: '/private', failureRedirect: '/login' }));
当我 console.log(user) 它返回
{
_id: 60cbb580ef0690505762a581,
username: 'qw@wp.pl',
createdAt: 2021-06-17T20:50:08.570Z,
__v: 0
}
但成功register
后返回
{
_id: 60cbb580ef0690505762a581,
username: 'qw@wp.pl',
hash: 'b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b7db0f56b8143e8607bf72ce2a565c38eeeb1f916cc9c0a85d8e6d3c9fe',
salt: '0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581',
createdAt: 2021-06-17T20:50:08.570Z
}
在DB
中:
_id:ObjectId("60cbb580ef0690505762a581")
username:"qw@wp.pl"
hash:"b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b..."
salt:"0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581"
createdAt:2021-06-17T20:50:08.570+00:00
__v:0
为什么用户数据在 register
之后有 hash 和 salt,而在尝试 login
时没有?
LogUser
架构:
const LogUserSchema = new mongoose.Schema({
name: {
type: String
},
email: {
type: String,
// required: true,
// unique: true
},
password: {
type: String,
// required: true
},
image: {
type: String
},
createdAt: {
type: Date,
default: Date.now
},
hash: {
type: String
},
salt: {
type: String
}});
我已经想不通出了什么问题。 很高兴收到任何答案!
答案 0 :(得分:0)
编辑以显示结果是正确的答案:
我认为 Mongoose 默认会从这些类型的查询中删除 hash 和 salt 字段。因此,要使您的查询正常工作,您只需键入 LogUser.findOne({username: username}, 'username salt hash')
,然后应该可以在返回的文档中访问 salt 和 hash。