首页 文章

如何根据loopback.js中的角色实现属性级别掩码?

提问于
浏览
0

我在loopback应用程序中创建的角色很少 . 有什么方法可以根据用户的角色隐藏模型的某些属性?

1 回答

  • 1

    是 . 您可以创建一个函数,并根据用户的角色在该函数中删除某些特定字段 . 应在要应用此规则的每个远程方法之后调用此函数(可以使用*在所有远程方法之后应用此函数) .

    这是一个示例代码,我希望它可以帮助您:

    const filterBasedOnRole= function (ctx, remoteMethodOutput, next) {
        const RoleMapping = SampleModel.app.loopback.RoleMapping;
        if (ctx.req.accessToken && ctx.req.accessToken.userId) {
          RoleMapping.findOne({
            where: { principalId: ctx.req.accessToken.userId },
            include: 'role',
          }, (err, roleMapping) => {
            if (err) { return next(err); }
            if (!roleMapping) {
              //User doesn't have a role
            } else {
              const role = roleMapping.role().name;
              if (role === 'admin') {
                 // Remove some fields from remoteMethodOutput
              }
            }
            next();
          });
        } else {
          // This user is not logged in, So it is a guest!
          next();
        }
    };
    
    SampleModel.afterRemote('search', filterBasedOnRole);  // Search is an example method, you can use whatever you want!
    

相关问题