LoopBack操作钩子过滤数据

最近项目使用node.js+LoopBack+mongdb+mysql框架。在权限控制时候需要根据用户的权限去加载其能看到的数据。因此对loopback的操作钩子进行了研究处理。

代码如下:首先在server.js中使用中间件进行用户权限设置的操作。包括其能看到某些id的数据。此处必须在中间件中定义,否则在LoopBack的上下文对象中是得不到req和res数据的。

app.use(function setCurrentUser(req, res, next) {
    var loopbackContext = loopback.getCurrentContext();
    var adminlogined = req.session.adminlogined || false;
    if (adminlogined) {
        loopbackContext.set('parkinglotIds', (req.session.adminUserInfo && req.session.adminUserInfo.parkinglotIds));
        loopbackContext.set('isadmin', req.session.isadmin || false);
    }
    else {
        loopbackContext.set('parkinglotIds', ["lebo"]);
        loopbackContext.set('isadmin', false);
    }
    next();
});

然后在common中的需要控制数据的表结构的js文件中做如下修改:

var loopback = require('loopback');
module.exports = function (Parkinglot) {
    Parkinglot.observe('access', function logQuery(ctx, next) {
        var lctx = loopback.getCurrentContext();//此处获得设置的数据
        var parkinglotIds = lctx && lctx.get("parkinglotIds");
        var isadmin = lctx && lctx.get("isadmin");

//以下代码根据自己需要进行修改
        if ((!parkinglotIds) || isadmin || ctx.options.charging) {
            next();
        }
        else {
            var i = 0;
            var original = null;
            for (var name in ctx.query.where) {
                i++;
                original = ctx.query.where;
            }
            if (i > 0) {
                if (ctx.query.where.and) {
                    ctx.query.where.and.push({ id: { inq: parkinglotIds } });//如果限制了当前表只能查看某些id的数据。则在此处增加查询条件即可。
                }
                else {
                    ctx.query.where = {};
                    ctx.query.where.and = [];
                    ctx.query.where.and.push({ id: { inq: parkinglotIds } });
                    if (original) {
                        ctx.query.where.and.push(original);
                    }
                }
            }
            else {
                ctx.query.where = {};
                ctx.query.where.and = [];
                ctx.query.where.and.push({ id: { inq: parkinglotIds } });
            }
            next();
        }
    });
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值