hugo der hungrige February 2016

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

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

Answers


nsbm February 2016

I strongly suggest you to extend the builtin User model even if the you does not need to create any new property. It's easy to extend using the arc console or creating the file manually and the entire process of authentication/authorization will work normally without any other additional configuration. Take a look here: https://docs.strongloop.com/display/public/LB/Extending+built-in+models

But even so if you want to use the builtin model User make sure that it is persisted in the database to show in the relationships manager list https://docs.strongloop.com/display/public/LB/Creating+database+tables+for+built-in+models

Post Status

Asked in February 2016
Viewed 3,482 times
Voted 6
Answered 1 times

Search




Leave an answer