protect user fields when returned via sequelize association

55 Views Asked by At

I'm having trouble figuring out how to exclude certain fields from the associated model from being returned in a query.

I've got a user-membership setup working, using a "users" model, which is associated to the "groups" model via a many-to-many relationship like this:

    users.belongsToMany(models.groups, {through:'group_users'});
    groups.belongsToMany(models.users, {through:'group_users'});

When I do a feathers GET for a specific group record, using a sequelize.include statement , the corresponding users are all returned in a "users" array along with the group.

    {
    id:123,
    name:"testGroup"
    users:[
       {
    id:1,
    firstname:"bob"
    email:"[email protected]"
    password:"pass"
       },
    
       {
    id:2,
    firstname:"doug"
    email:"[email protected]"
    password:"pass"
       }
    ]

So far so good. Except I want to hide the email and password fields in the returned data...

I have tried setting a defaultScope on the users model to exclude:["password", "email"], and that definitely works, but it also breaks the authentication plugin, so I can't login anymore...

I have tried the hooks-common "protect" method, to protect("password"), and also tried protect("users.password"), but neither had any affect.

How am I 'supposed' to accomplish something like this? Do I have to build a custom 'after' filter hook? Is there a way to accomplish this at the model or class level so that 'most' of the time these fields aren't returned, except when specifically requested?

Thanks!

1

There are 1 best solutions below

2
Youzef On

In the /services folder, go to the groups service you are getting the data from(your groups /GET path not the /users), and in the groups.hook.js add

const { protect } = require("@feathersjs/authentication-local").hooks;

module.exports = {
  after: {
    all: [],
    find: [      
      protect(
        ["users.email"]
        ["users.password"]
      ),
    ],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: [],
  },
};