While working with user authentication I am facing infinite loop during redirection.
Here is the peice of code from app.js:
const hauthen = require('./handlers/hauthen');
const routes = require('./routes/index');
const authen = require('./routes/authen');
const users = require('./routes/users');
app.use(hauthen);
// routes
app.use('/', routes);
app.use('/authen', authen);
app.use('/users', users);
And this code is from the authentication page hauthen.js:
router.all("/authen", (req, res, next) => {
if (req.authen) {
res.redirect("/");
} else {
next();
}
});
router.all("*", function(req, res, next) {
if (req.authen !== undefined) {
next();
} else {
res.redirect('/authen');
}
});
The basic idea is to redirect to login page if the user is not already authenticated. But I am getting this in console for the root url "/".
GET / 302 16.464 ms - 58
GET /authen 302 2.930 ms - 58
GET /authen 302 1.587 ms - 58
GET /authen 302 0.854 ms - 58
GET /authen 302 1.467 ms - 58
GET /authen 302 1.878 ms - 58
GET /authen 302 0.681 ms - 58
So, what is causing the problem of infinte redirection and how to fix it? Am I doing it in wrong way?