环回上下文不可靠-寻找替代方案

时间:2018-08-02 07:47:01

标签: javascript node.js loopbackjs

在验证用户身份后,我一直在使用 loopback-context 设置中间件中的当前用户对象。由于回送上下文不可靠,因此我尝试了一种替代方法,方法是从每个api调用的请求中获取accessToken并使用accessTokenId设置用户对象。

但是,在我的 mixins 中,我有一个before save钩子可以使用当前的user_id更新created_by和Modifyd_by值,而我无法在此处获取当前用户。

在server.js中设置用户对象的代码如下:

app.use(function (req, res, next) {
    if (!req.accessToken) return next();
    app.models.Users.findOne({
       where:
       {id: req.accessToken.userId},
       include: "roles"
    }, (err, user) => {
    if (err) {
       return next(err);
    }
    if (!user) {
       return next(new Error("No user with this access token was 
          found."));
    }
    res.locals.currentUser = user;
    next();
    });
});

mixins中的代码如下:

    Model.observe('before save', (ctx, next) => {
        var loopbackContext = LoopBackContext.getCurrentContext();
        var currentUser = loopbackContext && 
            loopbackContext.get('currentUser');
        let data = ctx.instance || ctx.data;
        if (ctx.isNewInstance && data) {
            // current user not available here
            data.created_by = currentUser && currentUser.id;
            data.modified_by = currentUser && currentUser.id;
        } else if (!ctx.isNewInstance && data) {
            data.modified_at = new Date();
            data.modified_by = currentUser && currentUser.id;
        }
        next();
    });

1 个答案:

答案 0 :(得分:0)

您可以改用ctx对象。这是我在项目中出于相同要求使用的示例Mixin。

//created-modified-injection.js
module.exports = function(Model, options) {
    'use strict';
    Model.defineProperty('created_by', {type: Number});
    Model.defineProperty('updated_by', {type: Number});
    Model.defineProperty('created_date', {type: Date});
    Model.defineProperty('updated_date', {type: Date});    
    Model.observe('before save', function event(ctx, next) {
        const token = ctx.options && ctx.options.accessToken;
        const userId = token && token.userId;
        let date = new Date();
        if (ctx.instance) {
            if (ctx.isNewInstance) {
                ctx.instance.created_by   = ctx.instance.created_by || userId;
                ctx.instance.created_date   = date;
            }else{
                ctx.instance.updated_by   = ctx.instance.updated_by || userId;
                ctx.instance.updated_date   = date;
            }
        }
next();
    });
};

并在模型的混合中启用它

"CreatedModifiedInjection": true