I'm using the built in user model of loopback for my application. What I want to accomplish is, that the author of a specific model entry (an article for example) is automatically saved to the model identified by the access token when it's saved.
I tried to implement this, by using the relationship manager, but the built in user model is not listed there.
Optimally when querying all articles, I would like the username to be available to show it in an overview but only if the current user is authenticated.
** Update **
After quite some research I found at least a way to add the current user to the loopback-context:
// see https://docs.strongloop.com/display/public/LB/Using+current+context
app.use(loopback.context());
app.use(loopback.token());
app.use(function setCurrentUser(req, res, next) {
console.log(req.accessToken);
if (!req.accessToken) {
return next();
}
app.models.user.findById(req.accessToken.userId, function (err, user){
if (err) {
return next(err);
}
if (!user) {
return next(new Error('No user with this access token was found.'));
}
var loopbackContext = loopback.getCurrentContext();
if (loopbackContext) {
loopbackContext.set('currentUser', user);
}
next();
});
});
Now I'm trying to add the user via a mixin:
module.exports = function (Model) {
Model.observe('before save', function event(ctx, next) {
var user;
var loopbackContext = loopback.getCurrentContext();
if (loopbackContext && loopbackContext.active && loopbackContext.active.currentUser) {
user = loopbackContext.active.currentUser;
console.log(user);
if (ctx.instance) {
ctx.instance.userId = user.id;
} else {
ctx.data.userId = user.id;
}
}
next();
});
};
I also opened an issue on github.