简体   繁体   中英

Hashing password on hapi.js is not working

in my database, password are stored using hashing. But when i try to send plain password to compare with stored password on db it's not working. I'm using bcrypt npm to hash password. I'm using hapi.js server.

//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();

but unfortunately every time when i give password, i get this error :

Debug: internal, implementation, error TypeError: Cannot read property 'password' of null

Debug: internal, implementation, error TypeError: Cannot read property 'username' of null

 usermodel.findOne({username, password})

That won't match any user, as the password you are using for searching is the unencrypted one, while the ones in the database are encrypted. Instead only search for the username, and exit early if that wasn't found:

const user = await usermodel.findOne({ username }).exec(); 
if(!user) return { isValid: false };

Hash the password first, then run your query:

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;
};

No further checks are necessary. The findOne() command will go through all users and return the first match for both the username and password field, or null if there is no match. Which means if the line returns a user , then username === user.username and pwHash === user.password implicitly .

The final line will return true if a match was found in the database, or false if no match was found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM