15

I want to do a filter like rails before filter on express.js. I have a file named photo.js where I'm putting all my photo related routes on there. But I need to redirect user that is not authenticated on my system to the login page. I want to do an beforeFilter so then I dont need to put that logic in all my routes...

Thanks

rizidoro
  • 13,073
  • 18
  • 59
  • 86

3 Answers3

18

If you want to keep everything in your photo.js file, I think a better approach is to use app.all and pass multiple callbacks (which work like middleware in routing) built into the app routing. For instance

app.all('/photo/*', requireAuthentication, loadUser);

app.get('/photo/view', function(req, res) {
   res.render('photo_view');
});

app.get('/photo/list', function(req, res) {
   res.render('photo_list');
});

Where requireAuthentication and loadUser are functions.

Take a look the documentation for app.VERB and app.all at http://expressjs.com/api.html#app.all

Dave Jensen
  • 4,574
  • 1
  • 40
  • 45
  • 2
    Using `all` is a great approach. I'm using it on top of `express-`resource for my routes, and it compliments it very well for authentication and authorization. – User 1058612 Nov 20 '13 at 02:21
3

There are extensions or higher-level frameworks like express-resource.

alessioalex
  • 62,577
  • 16
  • 155
  • 122
tjholowaychuk
  • 3,026
  • 1
  • 21
  • 6
  • How does express-resource helps in chain of responsibility / filter like problem here? Basically the github doesn't give any examples, you have one? – manocha_ak Jan 17 '14 at 12:59
3

The rails before_filter concept maps closely to the middleware concept from connect, which is part of express. You can set this up manually by preceding each photo related route with your authentication function, or use something high-level like TJ has mentioned. To do it manually would just be a matter of something like this (pseudo-coffeescript)

myAuthMiddleware = (req, res, next) ->
  if not req.session.user?
    res.redirect "/"
  else
    next()

editPhoto = (req, res) ->
  ....

deletePhoto = (req, res) ->
  ....

app.use(myAuthMiddleware, func) for func in [editPhoto, deletePhoto]

What that is saying is use myAuthMiddleware like a before_filter for the editPhoto and deletePhoto middleware functions.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274