Hapi.js 用户身份验证 mongodb 问题

Hapi.js user authentication with mongodb issue

为了用户验证,我现在直接在我的代码中硬编码了用户名和密码。但我希望动态使用数据库用户名和密码。因为,我是 hapi.js 的新手,这对我来说似乎很难。这是我的代码:

app.js

const auth = require('hapi-auth-basic');
const hapi = require('hapi'); 

mongoose.connect('mongodb://localhost:27017/db', { 
 useNewUrlParser: true }, (err) => {
   if (!err) { console.log('Succeeded.') }
   else { console.log(`Error`)}
 });

const StudentModel = mongoose.model('Student', {
  username: String,
  password: String
});

const user = {
   name: 'jon',
   password: '123'
};
 const validate = async (request, username, password, h) => {

let isValid = username === user.name && password === user.password;
    return { 
        isValid: isValid, 
        credentials: {
            name: user.name
          } 
       };
   };

 const init = async () => {

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

   server.route({
      method: 'GET',
      path: '/',
      handler: async (request, h) => {
           return 'welcome';
      }
 });
 }

我尝试通过如下更改 validate 来做到这一点:

const validate = async (request, username, password, h) => {

let isValid = username === request.payload.name && password === request.payload.password;
    return { 
        isValid: isValid, 
        credentials: {
            name: request.payload.name
        } 
    };
 };

但我得到了类型错误 "name",因为它很自然。我该如何修改它?

在这里,获取用户并检查验证方法

const validate = async (request, username, password, h) => {    
    // fetch user here 
    const user = await StudentModel.findOne({username, password}).exec();    
    // user doesn't exist
    if(!user) return {isValid: false}

    // just make sure here user really exists
    return {
        isValid: true,
        credentials: {
                name: user.name
        }
    }    
}