Reputation: 1380
Here's the scenario.
If a user wants to see a page that requires user access, I want to redirect him to the homepage, but I get ERR_TOO_MANY_REDIRECTS error when I try to access the homepage.
I couldn't figure it out how to solve this.
app.js
exports.ensureAuthenticated = function (req, res, next) {
jwt.verify(req.cookies.userToken, "NICETRY", function (err, decoded) {
if (err) {
res.redirect("http://localhost:4000");
} else {
// no err
if (decoded.id) {
req.id = decoded.id;
req.iat = decoded.iat;
next();
} else {
res.send("invalid cookie");
}
}
});
};
routes/frontend/index.js
var express = require('express');
var router = express.Router();
var indexController = require('../../controllers/frontend/indexController');
var auth = require('../../app').ensureAuthenticated;
router.get('/', auth, indexController.index);
module.exports = router;
indexController.js
exports.index = function (req, res) {
res.render('frontend/home/index');
};
Upvotes: 3
Views: 7873
Reputation: 64
The issue is that you're redirecting back to the same page once authentication fails and so your ensureAuthenticated middleware runs again and redirects again.
Try making one authenticated route and one unauthenticated route.
router.get('/', indexController.index); // no auth necessary
router.get('/private', auth, indexController.private); // requires auth
Now if you fail auth when you visit /private it will redirect to / which will display to the unauthenticated user.
Upvotes: 5