Sunday 21 May 2017

Protect static folder with passport

I have an angular app with a bunch of files (js, html, css) and a nodejs app with passport auth. I'd like to do the following: 1: if i visit my site, i'd like to see a login page (i am actually) 2: when i successfully logged in, i'd like to be redirected to my angular app 3: without auth, i want every angular resource of mine (imgs, jsons, etc) to be inaccessible. So far i can put my app to a folder, set it to static, pass the ensureAuthenticated middleware (which successfully detects in any other case if i'm logged in) to it, but it will always say "unauthenticated" when i'm trying to access that static folder. Some example code:

function ensureAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return next();
    } else {
        //req.flash('error_msg','You are not logged in');
        res.redirect('/users/login');
    }
}

app.use('/app', ensureAuthenticated);
app.use('/app', express.static(path.join(__dirname, 'app')));

router.get('/users/login', function(req, res){
    res.render('login');
});
router.post('/users/login',
  passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
  function(req, res) {
    res.redirect('/');
  });

router.get('/', ensureAuthenticated, function(req, res){
    res.redirect('/app');
});

If i'm missing something obvious, please let me know or if i'm completely on the wrong track, please suggest me some solution! Thank You all!

Note: i'm fairly new to passport and not an express/nodejs expert by any means.



via user3130985

No comments:

Post a Comment