hapi.js上的哈希密码无法正常工作

问题描述 投票:-1回答:2

在我的数据库中,密码是使用散列存储的。但是当我尝试发送普通密码与db上的存储密码进行比较时,它无法正常工作。我正在使用bcrypt npm来哈希密码。我正在使用hapi.js服务器。

//user authentication
const validate = async (req, username, password, reply) => {

const user = await usermodel.findOne({username, password}).exec(); 

const match = await bcrypt.compare(password, user.password);

if(match) {
    let isValid = username === user.username;
    return isValid;
}
   return { 
         isValid: isValid, 
    };
 };

const init = async () => {

try {
   await server.register(auth);
   server.auth.strategy('simple', 'basic', {validate});
   server.auth.default('simple');

  await server.start();
  console.log('Server running at:', server.info.uri);
   } catch (err) {
    console.log(err);
   }
 };

 init();

但不幸的是,每当我给密码时,我都会收到此错误:

Debug:internal,implementation,error TypeError:无法读取null的属性'password'

Debug:internal,implementation,error TypeError:无法读取null的属性'username'

javascript node.js bcrypt hapijs
2个回答
0
投票

首先哈希密码,然后运行您的查询:

const validate = async (req, username, password, reply) => {
  const pwHash = await bcrypt.hash(password);
  const user = await usermodel.findOne({ username, password: pwHash }).exec();
  return user !== null;
};

无需进一步检查。 findOne()命令将遍历所有用户并返回usernamepassword字段的第一个匹配,如果没有匹配则返回null。这意味着如果该行返回user,则隐含地返回username === user.usernamepwHash === user.password

如果在数据库中找到匹配,则最后一行将返回true,如果未找到匹配,则返回false


0
投票
 usermodel.findOne({username, password})

这与任何用户都不匹配,因为您用于搜索的password是未加密的,而数据库中的const user = await usermodel.findOne({ username }).exec(); if(!user) return { isValid: false }; 是加密的。而是仅搜索用户名,如果未找到,则提前退出:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.