Filters on express.js

I want to make a rails-like filter before the filter on express.js. I have a file called photo.js where I post all my photography related routes. But I need to redirect a user who is not authenticated on my system to the login page. I want to do beforeFilter, so I donโ€™t need to put this logic on all my routes ...

thank

+11
express
Jan 6 '12 at 19:41
source share
3 answers

If you want to save everything in your photo.js file, I think the best approach is to use app.all and pass a few callbacks (which work as middleware in routing) built into application routing. For example,

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.

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

+14
Nov 30 '12 at 6:26
source share

There are extensions or higher level structures such as express-resource .

+3
Jan 06 2018-12-12T00:
source share

The rails before_filter concept is closely related to connect's middleware concept, which is part of the expression. You can configure this manually by following each photo-related route using the authentication function, or use something higher level, as mentioned in TJ. Doing it manually would be just a matter of something like this (pseudo-coffenscript)

 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 this means, use myAuthMiddleware , like before_filter for the middleware functions editPhoto and deletePhoto .

+3
Jan 13 '12 at 15:55
source share



All Articles