Skip to content
July 07, 2019

Feathers users service

services/users/users.service.js

const { Service } = require('feathers-knex')
const hooks = require('./users.hooks')

module.exports = function users(app) {
  const options = {
    name: 'users',
    Model: app.get('knex'),
    paginate: app.get('pagination')
  }

  app.use('/users', new Service(options))

  app.service('users').hooks(hooks)
}

services/users/users.hooks.js

const { restrictToOwner } = require('feathers-authentication-hooks')
const { authenticate } = require('@feathersjs/authentication').hooks
const { hashPassword } = require('@feathersjs/authentication-local').hooks
const { iff, isProvider, discard } = require('feathers-hooks-common')

module.exports = {
  before: {
    all: [],
    find: [authenticate('jwt'), restrictToOwner({ ownerField: 'id' })],
    get: [authenticate('jwt'), restrictToOwner({ ownerField: 'id' })],
    create: [hashPassword()],
    update: [authenticate('jwt'), restrictToOwner({ ownerField: 'id' }), hashPassword()],
    patch: [authenticate('jwt'), restrictToOwner({ ownerField: 'id' }), hashPassword()],
    remove: [authenticate('jwt'), restrictToOwner({ ownerField: 'id' })]
  },
  after = {
    all: [
      iff(isProvider('external'), discard('password'))
    ]
  }
}

Notice how we we keep the create method unprotected, this is so that new users could sign up. All of the other endpoints are protected using the combination of authenticate and restrictToOwner hooks so that only authenticated requests could read the data and so that users could only read their own data.