alexmingoia / mongoose-express-router

Create Express 4 router and middleware from Mongoose 4 model.
4 stars 4 forks source link

Private fields #3

Open dsernst opened 8 years ago

dsernst commented 8 years ago

Is there a way to set fields to private?

alexmingoia commented 8 years ago

What do you mean by private exactly? What's the use case?

You can control which fields (including virtuals) are included in toJSON() or toObject(): http://mongoosejs.com/docs/guide.html#toObject

dsernst commented 8 years ago

Yeah exactly, that is what I mean. I like the idea of this a lot I just don't want to lose server control of picking which fields the client has access to.

And in some cases I'd want to have a different select subset based on the req. E.g. If a user tries to access their own user information, you can show them their own email address, but no one else has access to it.

On Sunday, January 3, 2016, Alex Mingoia notifications@github.com wrote:

What do you mean by private exactly? What's the use case?

You can control which fields (including virtuals) are included in toJSON or toObject options. http://mongoosejs.com/docs/guide.html#toObject

— Reply to this email directly or view it on GitHub https://github.com/alexmingoia/mongoose-express-router/issues/3#issuecomment-168523269 .

David Ernst

alexmingoia commented 8 years ago

If you want that kind of control, one idea is to create some sort of plugin that wraps .toObject() with your own function that checks for access and what not.

alexmingoia commented 8 years ago

Thought about this some more... the code below should work for scrubbing individual properties in combination with mongoose-express-router.

toObject has a transform function option. The transform function below inspects the schema for properties with a roles option and matches that against req.session.role. Using this, toObject()/toJSON() excludes any property for which the session doesn't have the required role.

Schema.set('toObject', {
  transform: function (doc, ret, options) {
    var schema = doc.schema;
    var scrubbed = {};

    Object.keys(ret).forEach(function (key) {
      var opts = schema.paths[key] && schema.paths[key].options;
      if (ret[key] !== undefined) return;
      if (opts && opts.roles && !~opts.roles.indexOf(doc.session.role)) return;
      scrubbed[key] = ret[key];
    });

    return scrubbed;
  }
});