0

Regarding to this post: https://stackoverflow.com/a/69903276/1547821 it shows an approach with less boilerplate, to prevent a users query output (GET) to only the user who is logged in.

But how to do this, to get i.e. all members of the related group which the logged-in user participates?

This example below is my hook, but i want to have it in before->find hook as a query injection or addition.

module.exports = (options = {}) => {
  return async context => {
    const groupMembers = await context.app.service('groups').options.model.relatedQuery('users').for(context.params.user.id)
    console.log(groupMembers)
    return context
  }
}

It doesn't help me as after->find hook, because total and etc. doesn't match then. Aswell my keeps doesn't work.

Appreciating any hints.

2 Answers2

0

One solution would be to add a userId column to your groups model. This will contain a user of the group.

//in your /services/groups.hook.js
const { authenticate } = require('@feathersjs/authentication').hooks;
const { setField } = require('feathers-authentication-hooks');

module.exports = {
  before: {
    all: [],
    find: [
      authenticate('jwt'),
      setField({
        from: 'params.user.id',
        as: 'params.query.userId',
      }),
    ],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: [disallow('external')],
  },

  //after and error options go here
};

This should return only results where the logged in user's Id matched the Id in the group table.

Ps: try console logging the context object for more insight. Also the userId column in groups model should be associated to the id column of users model.

Youzef
  • 616
  • 1
  • 6
  • 23
0

Thanks. Meanwhile I found a solution for the before->find.hook:

context => {
    if(context.params.user !== undefined) {
      const groupMembers = await context.service.options.model.relatedQuery('groups').for(context.params.user.id)
      if(groupMembers) {
        context.params.query['$joinEager']  = 'groups'
        context.params.query['groups.id']  = groupMembers[0].id
      }
    }
    return context;
  };