0

If I register middleware in server/middleware.json, this middleware is executed for each request, regardless of its kind. But for authorization checks, I need execution only for calls of API paths. How can I achieve this?

ideaboxer
  • 3,863
  • 8
  • 43
  • 62
  • 1
    The below answer aside, are you not using the built-in auth mechanism for loopback for some reason? The user model has auth out of the box, so to speak. See `server/boot/authentication.js`. – notbrain Jul 20 '15 at 02:08
  • It is an additional kind of authorization. Not user-based, but preshared-secret-based. I would like to check in the middleware, if the secret is present in the form of a database query filter option. Anyway: If there is some built-in method to achieve this, I would definitely prefer the built-in way. – ideaboxer Jul 20 '15 at 09:34

1 Answers1

1

Create a file inside server/boot, like this example I made to preview email templates in a browser for development. You just add an express route as you would inside an express app:

// from the loopback custom express route docs:
//
// module.exports = function(app) {
//   var router = app.loopback.Router();
//   router.get('/ping', function(req, res) {
//     res.send('pong');
//   });
//   app.use(router);
// }
var fs                 = require('fs');
var Mustache           = require('mustache');
var path               = require('path');

module.exports = function(app) {
  app.get('/emails/:template', function(req, res) {

    var data = {
      // data for template render
    };

    var template = fs.readFileSync(path.resolve(__dirname, '../../client/views/emails/' + req.params.template), 'utf-8');
    var html = Mustache.render(template, data);

    res.send(html);

  });

}

http://localhost:3000/ping should output "pong".

See http://docs.strongloop.com/display/public/LB/Add+a+custom+Express+route

So, if you need something to fire on all API events, instead of an explicit path as above you could try:

app.all('/api/*', requireAuthentication);

to match on the /api prefix to run that middleware.

See: http://expressjs.com/api.html#app.all

notbrain
  • 3,366
  • 2
  • 32
  • 42