环回上下文不可靠-正在搜索替代方案



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

然而,在我的mixins中,我有一个保存前挂钩来用当前user_id更新created_by和modified_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();
});
});

mixin中的代码如下:

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();
});

您可以使用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

相关内容

最新更新