Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to protect static folder in express with passport

How to protect static folder in express with passport

Problem

I have a project based on express with a required authentication based on passport.

The backoffice is an angularjs app served as static files.

My authentication code is completly based on https://github.com/jaredhanson/passport-local/blob/master/examples/express3-no-connect-flash/app.js

To do not serve the angular app if you are not authenticated. I have try by adding ensureAuthenticated on the /admin route but it make the route not working (404). Once I remove ensureAuthenticated the /admin is served.

app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', ensureAuthenticated, express.static(path.join(__dirname, 'admin')));
//serve routes
app.use(app.router);

The public folder contains the login page.

How could I achieve this ?

Problem courtesy of: toutpt

Solution

You can check the route using middleware and redirect them if they aren't logged in and are hitting admin pages, something like (untested):

app.use(function(req, res, next) {
    if (req.user == null && req.path.indexOf('/admin') === 0)
    {
        res.redirect('/login');
    }
    next(); 
});
Solution courtesy of: MikeSmithDev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to protect static folder in express with passport

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×