Loopback NodeJS - 在登录时检查用户角色

时间:2018-01-30 14:16:05

标签: node.js rest http loopback apiconnect

我有一个应用程序使用Angular 5作为前端,NodeJS作为后端,我使用loopback来创建API。我有一个远程方法,我用来登录用户,这是有效的。现在我想更改此方法以检查用户是否是管理员,但我无法这样做。出于某种原因,当我对RoleMappings模型进行API调用时,使用/ api / RoleMappings?filter = {where:{“principalId”:ID_VALUE}它不起作用。 ID_VALUE也是admin的user_id,因为这个角色和admin是以编程方式创建的,所以我知道principalId应该是userId。

我正在请求检查角色是否为嵌套请求,首先我检查用户是否已登录(如果用户甚至没有登录,那么检查他是否是管理员是没有意义的话),然后我检查该用户是否恰好是管理员。这是代码,任何帮助将不胜感激。

我使用IBM API connect测试了API调用,并且它工作正常,它只是不想使用我的代码。此请求不会引发错误,但响应包含400代码且正文为空。

存储角色映射的DB是CloudantDB

var options = {
            method: 'POST',
            url: conf.endpoint + 'api/Clients/login',
            headers: this.headers,
            body: user,
            json: true
        }

        request(options, function (error, response, body) {
          if (error) return callback(error);

            //
            var adminOptions = {
            method: 'GET',
            url: conf.endpoint + '/api/RoleMappings',
            qs: {filter: {"where":{"principalId": "\""+body.userId"\"","roleId":"159882e4a5bdde9cc725eee8c13a1030"}}},
            headers: this.headers 
          }

          request(adminOptions, function(aReqErr, aRes, aBody){
            if(aReqErr) return callback(aReqErr);

            //console.log("Admin check success: ", aRes);
            if(aBody){
            var pId = aBody[0].principalId;
            console.log("Admin check success:", aBody);
            if(pId){
                body["isAdmin"] = true;
            }else{
                body["isAdmin"] = false;
            }
        }else{

            console.log("aResCode", aRes.statusCode);
            console.log("aResMessage", aRes.statusMessage);
            //console.log("aReqErr", aReqErr);
        }

          });

          //console.log('Success: ', typeof body);

          callback(null, body);

        });

1 个答案:

答案 0 :(得分:0)

我会仔细检查RoleMapping模型是否在model-config.json公开公开,这是发送GET请求所必需的。

我在模型代码中完成了类似的查询,如下所示:

app.models.RoleMapping.find({
  where: {
     principalId: userId,
     roleId: roleId
  }
}, cb)

鉴于您的过滤字符串如下所示:

?filter={"where":{"principalId":<userId>,"roleId":<roleId>}}

我希望它能够根据我的经验运作。只有我能想到的其他事情可能是userId的格式不正确,你可以尝试删除它周围的转义引号,如下所示:

qs: {
  filter: {
    where: {
       principalId: body.userId,
       roleId: "159882e4a5bdde9cc725eee8c13a1030"
    }
  }
}