Feathers - Limit service response to data owned only by the current user
In Pens, the goal is to restrict the availability of data on a particular service to data owned only by a logged in user.
Assuming I am using Feathers authentication, the data available in this service is stored in the database table and the table column containing the user id is called user_id
, will this hook achieve the goal?
If not, what needs to be changed?
In case it is important to be able to answer the question, I use Sequelize and Postgres.
const { authenticate } = require('feathers-authentication').hooks;
const { queryWithCurrentUser } = require('feathers-authentication-hooks');
const { associateCurrentUser } = require('feathers-authentication-hooks');
const readRestrict = [
queryWithCurrentUser({
idField: 'id',
as: 'user_id'
})
];
const modRestrict = [
associateCurrentUser({
idField: 'id',
as: 'user_id'
})
];
module.exports = {
before: {
all: [ authenticate('jwt') ],
find: [ ...readRestrict ],
get: [ ...readRestrict ],
create: [ ...modRestrict ],
update: [ ...modRestrict ],
patch: [ ...modRestrict ],
remove: [ ...modRestrict ]
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
This seems to work, but since I'm a Feathers noob, I thought I'd better check before it gets put into the wild to make sure there isn't a case where I don't know it will cause leaks.
source to share
As a total newbie to pens and expressions, I'm not sure. Everything now works as above.
Old answer
As remove
I have used restrictToOwner
. (I also think for patch
and update
, because they work with existing data. However, I have not tested this.) Otherwise, I was able to cross-delete the data by specifying an ID. Maybe you can also check if this is right for you.
This is a test case:
- user 1 creates a model object with
- user id for authorization check
- object identifier to identify the object
- user 2 deletes object with object id
- test ok: 404 expected
- Verification failed: 204 or 200.
- User 1 is trying to get an object
- test ok: there is an object, 200
- test fail: no object, 404
Test code:
Thanks a lot, you really helped me!
source to share