javascript - How to automatically add the current user to a model on save? -


i'm using built in user model of loopback application. want accomplish is, author of specific model entry (an article example) automatically saved model identified access token when it's saved.

i tried implement this, using relationship manager, built in user model not listed there.

optimally when querying articles, username available show in overview if current user authenticated.

** update **

after quite research found @ least way add current user 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 access token found.'));     }     var loopbackcontext = loopback.getcurrentcontext();     if (loopbackcontext) {       loopbackcontext.set('currentuser', user);     }     next();   }); }); 

now i'm trying add user via 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 opened issue on github.

i know question old might people

in loopback 2.x, need add model json

"injectoptionsfromremotecontext": true 

then:

model.observe('before save', function(ctx, next) {   if(ctx.instance){      ctx.instance.userid = ctx.options.accesstoken.userid;   }else if (ctx.data){      ctx.data.userid = ctx.options.accesstoken.userid;   }   return next(); }); 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -