Reputation: 651
I'm a newbie in node.js and I'm trying to redirect all the routes after localhost:4000/ if it is not logged in. And it gives me error with "Too many redirects"...
my code that using app.get
in app.js
app.get('*', loggedInCheck);
and below code is loggedInCheck function that I've written,
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
However, it keeps giving me an error as "Too many redirects" and doesn't go through login page because it is not authenticated yet.
What is my problem here? and how can I fix this....?
Can anybody help me out here??
Just in case, I'll put my whole code from app.js
app.js
var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Connecting Database (MongoDB)
mongoose.connect("my private mongoDB address");
var db = mongoose.connection;
db.once("open",function () {
console.log("DB connected!");
});
db.on("error",function (err) {
console.log("DB ERROR :", err);
});
//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");
//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
email: {type:String, required:true, unique:true},
password: {type:String, required:true},
createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
var user = this;
if(!user.isModified("password")){
return next();
} else {
user.password = bcrypt.hashSync(user.password);
return next();
}
});
//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
var user = this;
return bcrypt.compareSync(password,user.password);
};
//Setting User as userSchema.
var User = mongoose.model('user',userSchema);
io = io.listen(server);
//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());
app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
//Initializing passport.
passport.serializeUser(function(user, done) {
//console.log('serializeUser()', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
//console.log('deserializeUser()', user);
User.findById(id, function(err, user) {
done(err, user);
});
});
var global_username = ''; //Global variable for username to put in the address
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email }, function(err, user) {
if (err) return done(err);
if (!user){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'No user found.'));
}
if (!user.authenticate(password)){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'Password does not Match.'));
}
var email_address = req.body.email;
var username = email_address.substring(0, email_address.lastIndexOf("@"));
global_username = username;
return done(null, user);
});
}
)
);
//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html
app.get('*', loggedInCheck);
app.get('/login', function (req,res) {
res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});
//Accessing to MongoDB to check to login or not
app.post('/login',
function (req,res,next){
next();
}, passport.authenticate('local-login', {
successRedirect : '/status',
failureRedirect : '/login',
failureFlash : true
})
);
//Logging out
app.get('/logout', function(req, res) {
req.logout();
console.log("Logging out the account!");
res.redirect('/login');
});
//Creating new account
app.get('/users/new', function(req,res){
res.render('users/new', {
formData: req.flash('formData')[0],
emailError: req.flash('emailError')[0],
passwordError: req.flash('passwordError')[0]
}
);
});
//If creating an account is successed, then goes back to login page.
app.post('/users', checkUserRegValidation, function(req,res,next){
User.create(req.body.user, function (err,user) {
if(err) return res.json({success:false, message:err});
res.redirect('/login');
});
});
//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
res.redirect('/status.html?channel=' + global_username);
});
//Calling Topology_view html
app.get('/topology', isLoggedIn, function(req, res){
console.log("Accessing to topology_view");
res.redirect('topology.html?channel=' + global_username);
});
//functions
//Check whether session is still on or not.
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()){
console.log("Authenticated");
return next();
}else{
console.log("Unauthorized Attempt");
res.redirect('/login');
}
}
//Initial checking whether session is on or not.
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
//Checking whether email is already in the database or not in sign up.
//If email is already in the database, it gives error message.
function checkUserRegValidation(req, res, next) {
var isValid = true;
async.waterfall(
[function(callback) {
User.findOne({email: req.body.user.email, _id: {$ne: mongoose.Types.ObjectId(req.params.id)}},
function(err,user){
if(user){
isValid = false;
req.flash("emailError","- This email is already resistered.");
}
callback(null, isValid);
}
);
}], function(err, isValid) {
if(err) return res.json({success:"false", message:err});
if(isValid){
return next();
} else {
req.flash("formData",req.body.user);
res.redirect("back");
}
}
);
}
//handler function is for topology.html.
function handler(req,res){
fs.readFile(__dirname + '/public/topology.html', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
fs.readFile(__dirname + '/public/style.css', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
}
io.sockets.addListener('connection', function(socket){
console.log("connceted : " + socket.id);
var subscriber = redis.createClient(6379, 'localhost');
subscriber.psubscribe("*");
subscriber.on("pmessage", function(pattern, channel, message) {
//console.log(message);
socket.emit(channel, message);
});
socket.on('disconnect', function () {
console.log("disconnceted : " + socket.id);
subscriber.quit();
});
socket.on('close', function() {
console.log("close");
subscriber.quit();
});
});
server.listen(4000);
Upvotes: 0
Views: 4174
Reputation: 1753
Your issue is in your loggedInCheck function. No matter what route you are on, you are checking if the user is authenticated otherwise redirect to login. So, even if your trying to get to the login page, it's gonna try and redirect again, and again forever.
app.get('*', loggedInCheck);
Isn't a good way todo it. You should have some sort of function that makes sure your not trying to go to a zone that is okay for non-users. Maybe something like this:
app.get('*', function(req, res, next){
if(req.url != '/login'){
loggedInCheck(req, res, next);
}else{
next();
}
});
Upvotes: 1