【问题标题】:Hapi.js user authentication with mongodb issueHapi.js 用户身份验证与 mongodb 问题
【发布时间】:2019-03-11 09:10:25
【问题描述】:

对于用户验证,我现在直接在我的代码上硬编码了用户名和密码。但我想动态地使用数据库用户名和密码。因为,我是 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
        } 
    };
 };

但我得到了类型错误“名称”,因为它很自然。我该如何修改?

【问题讨论】:

    标签: javascript node.js mongodb authentication hapijs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2017-02-08
      • 2016-11-27
      相关资源
      最近更新 更多