Middleware not redirect

I'm writing a simple system to control authentication for users, only registered users have access to the site. If you are not authenticated redirect you to the login page.

Quite simply I'm using a middleware to make this control.

My problem is that when the condition for the redirection is valid, this does not happen!

// Routes
module.exports = function(app) {
app.use(function(req, res, next) {
    console.log(req.url);

    if (typeof(res.session) == 'undefined' && req.url != '/users/login') {
        console.log('redirect');
        res.redirect('/users/login');
    } else {
        console.log('no redirect');
        next();
    }
});

app.get('/',                    routes.site.index);

app.all('/users/login',         routes.user.login);
};

Obviously, the stout console is:

/
redirect
/users/login
no redirect

And the page is loading indefinitely...

Any suggestions?

Thanks!

PS: I apologize if I misspelled, Google helped me!

@-------------------- EDIT:

I opted to use Passport for the management of Auth.

I only have one problem, I run the routes of my app in a separate file.

app.js

// Auth
var passport = require('passport'), strategy = require('passport-local').Strategy;
passport.use(new strategy(function(username, password, done) {
var user = require('./db')('user');

user.findOne({username: username}, function(err, user) {
    if (err) return done(err);
    if (!user) return done(null, false);
    if (!user.validPassword(password)) return done(null, false);

    return done(null, user);
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
var user = require('./db')('user');

user.findOne(id, function(err, user) {
    done(err, user);
});
});
// End Auth

require('./routes')(app, passport);

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

routes/index.js

// Routes
module.exports = function(app, passport) {
    app.get('/', passport.authenticate('local', {successRedirect: '/', failureRedirect: '/login' }), routes.site.index);

    app.all('/login', routes.user.login);
};

routes/user.js

exports.login = function(req, res, next) {
    switch (req.method) {
        default:
        case 'GET':
            res.render('user/login', {title: 'Login'});
        break;
        case 'POST':
            /*passport.authenticate('local', function(err, user, info) {
                res.json([user, info]);
            });
            */
        break;
    }
};

The redirect to the login page works fine, but I would manage the routes in different files, and so I can not help maintain the variable passport to be able to handle the callback control in the file user.js.

Ideas? Thanks!!!

If you are using Connect's session middleware, most likely every request will have a session associated with it. You'll need to check if there's a user ID (or similar) set in the session to make the authenticated/unauthenticated determination.

I'm also the developer of Passport, which works alongside connect-ensure-login middleware to protect access to authenticated routes. I'd recommend looking at that, as it will allow you to get an authentication system up and running quickly.

do something like this instead:

if (user.loggedin === undefined && req.url != '/users/login')

I'm pretty sure Express gives a session for each requester; logged in or not. So, you need a check on login not on session.