Question

I'm working on a node.js application, using Angular.js, passport and connect-ensure-login.

Only on refresh (F5), does the redirect in ensureLoggedIn seem to work and I get to the login page, otherwise I think the routeProvider for the one-page app just takes over for normal click and I get to localhost:3000/users still with the 500 error from '/api/users'.

How can I get connect-ensure-login (ensureLoggedIn) working for both direct path and click-through?

app.get('/users', ensureLoggedIn('/login'))

For APIs, I'm using

app.get('/api/users', 
    passport.authenticate('bearer'),
    ...

routeProvider snippet for the application:

.config(function($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/home.html'
            })
            ...

References:

https://www.npmjs.org/package/connect-ensure-login

http://passportjs.org/

Was it helpful?

Solution

You may want to go about solving this issue by making use of the $httpProvider.interceptors.

In your case you could catch the 500 error coming from /api/users (though probably better to return a 401 or 403) and have an interceptor kick in and take the user to /login.

Here's the official doc:

http://docs.angularjs.org/api/ng/service/$http#interceptors

Here's a more specific example:

http://blog.thesparktree.com/post/75952317665/angularjs-interceptors-globally-handle-401-and-other

And here's a similar answer.

https://stackoverflow.com/a/18764801/115015

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top