【问题标题】:FeathersJS: How to cancel the authentication hook using an error from a hook after itFeathersJS:如何使用钩子后面的错误取消身份验证钩子
【发布时间】:2018-09-26 22:18:42
【问题描述】:

我在客户端使用了app.authenticate
它在服务器上创建钩子之前调用了身份验证钩子。
我从“feathers-authentication-manage.hook”导入为verifyHooks

创建钩子之前:

app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies),
        async context => {
          const { app, data } = context;

          await app.service('users').find({
            query: {
              usernameUpperCase: data.username.toUpperCase(),
              $limit: 1
            }
          })
          .then(async (user) => {
            await user.data.map(async data => {
              if(!data.isVerified) {
                await console.log('HELLO FROM ABOVE.');
                //await v.validationError('Verify Email. A token link has been sent to your email.');
              }
            });
          })
          .catch(err => v.validationError(err));
        },
        verifyHooks.isVerified()
      ],

按顺序排列的 3 个钩子是:
1. 认证
2. 我的钩子
3.isVerified()email 验证钩子来自羽毛认证管理

在客户端,当isVerified() 钩子激活时,即使是在身份验证钩子之后,身份验证承诺也会被拒绝。
如果我删除了 isVerified() 钩子,那么身份验证承诺就会解决。

如何使我的钩子(第二个钩子)的行为类似于 isVerified(),以便拒绝客户端上的身份验证承诺?

【问题讨论】:

    标签: promise async-await feathersjs feathers-authentication feathers-hook


    【解决方案1】:

    第一件事是你使用async/await 让你的生活变得更加艰难,而不是像预期的那样。这个想法是不必编写所有这些 .then.catch 处理程序。

    .catch 处理程序也可能是实际问题所在。如果.catch(在您的情况下为v.validationError(err))没有拒绝或抛出错误,则承诺将成功解决。使用async/await正确的方法和Promise.all等待异步验证步骤然后重新抛出验证错误应该可以做到:

    app.service('authentication').hooks({
        before: {
          create: [
            authentication.hooks.authenticate(config.strategies),
            async context => {
              const { app, data } = context;
    
              const user = await app.service('users').find({
                query: {
                  usernameUpperCase: data.username.toUpperCase(),
                  $limit: 1
                }
              });
    
              try {
                await Promise.all(user.data.map(async data => {
                  if(!data.isVerified) {
                    await console.log('HELLO FROM ABOVE.');
                    //await v.validationError('Verify Email. A token link has been sent to your email.');
                  }
                });
              } catch(err) {
                throw v.validationError(err);
              }
            },
    

    【讨论】:

    • 你是对的。我没有正确使用异步/等待。您的代码有效。我还删除了 then() 中的所有 async/await 以便我的工作。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2018-09-24
    相关资源
    最近更新 更多