Skip to content

Instantly share code, notes, and snippets.

@MichaelErmer
Last active April 15, 2018 17:47
Show Gist options
  • Save MichaelErmer/de604f08ac19655a7c4012091e4c94d8 to your computer and use it in GitHub Desktop.
Save MichaelErmer/de604f08ac19655a7c4012091e4c94d8 to your computer and use it in GitHub Desktop.

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.

@bertho-zero
Copy link

app.hooks(globalHooks);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment