foxhound87
11/24/2016 - 3:05 PM

globalHooks.md

This gist explains how to use the new app hooks with a generator project to secure all services. (All but login~)

https://blog.feathersjs.com/feathers-application-and-error-hooks-7a5982e70024#.fmmyo0thh

1. Update to feathers-hooks

npm install --save feathers-hooks@1.6.0

2. Add the following to src/hooks/index.js

const auth = require('feathers-authentication').hooks;
const hooks = require('feathers-hooks-common');

exports.before = {
  all: [
    function (hook) { 
      hook.service = Object.keys(hook.app.services).find(name => hook.app.services[name] === this);
    },
    hooks.iff((hook) => {
        return !hook.service.match(/^auth/);
      },
      auth.verifyToken()
    ),
    hooks.iff((hook) => {
        return !hook.service.match(/^auth/);
      },
      auth.populateUser()
    ),
    hooks.iff((hook) => {
        return !hook.service.match(/^auth/);
      },
      auth.restrictToAuthenticated()
    )
  ],
  find: [],
  get: [],
  create: [],
  update: [],
  patch: [],
  remove: []
};

exports.after = {
  all: [],
  find: [],
  get: [],
  create: [],
  update: [],
  patch: [],
  remove: []
};

3. In in src/app.js, import the hooks and apply them

const globalHooks = require('./hooks');
// Insert after app().configure(hooks()):
app.hooks({
  before: globalHooks.before,
  after: globalHooks.after
});

4. Done

Now remove the hooks from the individual services.