0

I am using passport.js for authentication. My requirement is that, anyone should not be able to access a particular page (say, '/restricted'), if one is not logged in.

Right now, in my application, anyone can access "localhost:3000/#/restricted" url directly.

I am able to stop this and allow only logged in users to access the page by using Rorschach120's solution in Redirect on all routes to login if not authenticated.

But this is done client side and is not that secure, because anyone can access this code from browser.

So I need that the request for my page goes to server, I tried moka's solution in How to know if user is logged in with passport.js?:

In app.js:

app.get('/restricted', loggedIn, function(req, res, next) {
// req.user - will exist
// load user orders and render them
});

where the loggedIn() function checks if user is logged in or not.

But this middleware is NEVER called and anyone can still access the "restricted" page. What can I do, so that this gets called?

I am new to AngularJS and NodeJS. Am I doing something wrong here? Any help will be appreciated.

Community
  • 1
  • 1
OutOfMind
  • 874
  • 16
  • 32

1 Answers1

0

You can use middleware for that purpose.

app.get('/secure-route', secureMiddleware, myMethod)

let secureMiddleware = function(req, res, next) {

    authCheck(...)
        .then(function(result) {
            // pass
            next()
        })
        .catch(function(err) {
            res.status(401).json({
                code: 401,
                message: 'restricted route'
            })
        })
}
Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
  • Yes, I tried this, as described in question. But this middleware never gets called. It directly gets redirected to the page requested. What might I be doing wrong? – OutOfMind Nov 30 '15 at 10:16
  • I have edited my question, mentioning that I am using a middleware similar to the one described in this answer, but it is not called. What should I do so that this is called to to check if user is authenticated? – OutOfMind Nov 30 '15 at 11:39
  • Did you set the express app to use the middleware? – Tuan Anh Tran Nov 30 '15 at 12:25
  • I have written app.use("path to the file containing middleware"), do I need to do anything else? – OutOfMind Nov 30 '15 at 12:30
  • Should be app.use(require("path here")). – Tuan Anh Tran Nov 30 '15 at 12:31
  • Okay, and what about client side Angular routing? I have defined the routing for '/restricted' in $routeProvider, is this alright? Or should I change anything there? – OutOfMind Nov 30 '15 at 12:33