【问题标题】:hapi-auth-basic validate function doesn't work properly when the function contains asynchronous code当函数包含异步代码时,hapi-auth-basic 验证函数无法正常工作
【发布时间】:2019-01-18 17:12:12
【问题描述】:

我在我的 hapi 服务器 v17.2.2 中使用 hapi-auth-basic 5.0.0 版进行身份验证。当验证函数中有异步代码时会出错。怎么办?

我使用 hapi-cli 创建了一个 hapi 项目。它有一个名为策略的文件夹,其中包含用于身份验证的验证功能。 为了方便起见,我对其进行了一些修改,如下所示

const Boom = require('boom');
const User = Models.User

module.exports = async (request, email, password, h) => {
    if (!email || !password) {
        return {
          isValid: false,
          credentials: null
        }
    }
    User.findOne({
        email,
        role: 'admin'
    }).exec((err, currentUser) => {
        if (!currentUser || err) {
            return Boom.badRequest('You must be admin user');
        }
        request.adminUser = currentUser;
        return {
          isValid: true,
          credentials: currentUser
        }
    });
};

如果给定的电子邮件地址存在并且用户角色是管理员,我想对用户进行身份验证 但我收到以下错误

Debug: internal, implementation, error 
    TypeError: Cannot destructure property `isValid` of 'undefined' or 'null'.
    at Object.authenticate (/home/sruthi/IoTRL/hapi-api/node_modules/hapi-auth-basic/lib/index.js:64:56)
    at <anonymous>

当我像这样返回 {isValid: true, credentials: {email}}

module.exports = async (request, email, password, h) => {
    if (!email || !password) {
        return {
          isValid: false,
          credentials: null
        }
    }
    return {
      isValid: true,
      credentials: {email}
    }
};

没有异步代码从数据库中获取用户,它工作正常。

【问题讨论】:

    标签: javascript node.js basic-authentication hapijs


    【解决方案1】:

    因为你的函数什么都不返回,Mongoose exec((err, user)) 超出了你的函数范围,而且你已经在使用异步函数,为什么不使用 await 语法。

    在这里,快速重写您的代码。

    module.exports = async (request, email, password, h) => {
        if (!email || !password) {
            return {
              isValid: false,
              credentials: null
            }
        }
    
        try
        {
            const user = await User.findOne({ email, role: 'admin' }).exec();
    
            // user doesn't exist
            if(!user){
                return Boom.unauthorized('You must be admin user');
            }
    
            // we found the user, let's authenticate
            request.adminUser = currentUser;
            return {
              isValid: true,
              credentials: currentUser
            }
        } catch(e){
            // handle other errors
            return Boom.badRequest(e);
        }   
    };
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2019-03-28
      • 2019-10-13
      • 2020-11-08
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      相关资源
      最近更新 更多