3
votes

I am learning mean stack by making a social media web app like twitter But at the time of signup or login i am getting success and a user also was created in database but the page does not redirects and gives error 500

The following is the code

App.js

var express = require('express');  
var path = require('path');  
var favicon = require('serve-favicon');  
var logger = require('morgan');  
var cookieParser = require('cookie-parser');  
var bodyParser = require('body-parser');  
var session = require('express-session');  
var passport = require('passport');  
var LocalStrategy   = require('passport-local').Strategy;  
require('./models/models.js');  
var index = require('./routes/index');  
var api = require('./routes/api');  
var authenticate = require('./routes/authenticate')(passport);  
var mongoose = require('mongoose');  
mongoose.connect('mongodb://localhost:27017/chirp-test');  

var app = express();    


app.set('views', path.join(__dirname, 'views'));  
app.set('view engine', 'ejs');  

app.use(logger('dev'));  

    app.use(session({
      secret: 'keyboard cat',
      resave: true,
      saveUninitialized: true
    }));  

app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: false }));  
app.use(cookieParser());  
app.use(express.static(path.join(__dirname, 'public')));  
app.use(passport.initialize());  
app.use(passport.session());  

var initPassport = require('./passport-init');  
initPassport(passport);  

app.use('/', index);  
app.use('/auth', authenticate);  
app.use('/api', api);    


app.use(function(req, res, next) {  
  var err = new Error('Not Found');  
  err.status = 404;  
  next(err);  
});    

app.use(function(err, req, res, next) {  
  res.locals.message = err.message;  
  res.locals.error = req.app.get('env') === 'development' ? err : {};    

  res.status(err.status || 500);  
  res.render('error');  

});  

module.exports = app;

authenticate.js

var express = require('express'); var router = express.Router();

module.exports = function(passport){

router.get('/success', function(req, res){
    res.send({state: 'success', user: req.user ? req.user : null});
});

router.get('/failure', function(req, res){
    res.send({state: 'failure', user: null, message: "Invalid username or password"});
});

//log in
router.post('/login', passport.authenticate('login', {
    successRedirect: '/auth/success/',
    failureRedirect: '/auth/failure'
}));

//sign up
router.post('/signup', passport.authenticate('signup', {
    successRedirect: '/auth/success',
    failureRedirect: '/auth/failure'
}));

//log out
router.get('/signout', function(req, res) {
    req.logout();
    res.redirect('/');
});

return router;

}

passport-init.js

var passport = require('passport');
var LocalStrategy   = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');

module.exports = function(passport){


    passport.serializeUser(function(user, done) {
        return done(null, user._id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user){
            if(err){
                return done(err, false);
            }
            if(!user){
                return done('User not found', false);
            }
            return done(user, true);
        })
    });

    passport.use('login', new LocalStrategy({
        passReqToCallback : true
    },
    function(req, username, password, done) {

        User.findOne({'username': username}, function(err, user){
            if(err){
                return done(err, false);
            }
            if(!user){
                return done('Username does not exist ', false);
            }
            if(!isValidPassword(user, password)){
                return done('Incorrect password', false);
            }
            return done(null, user);
        });
    }
));

    passport.use('signup', new LocalStrategy({
        passReqToCallback : true 
    },
    function(req, username, password, done) {

        User.findOne({'username' : username}, function(err, user){
            if(err){
                return done(err, false);
            }
            if(user){
                return done('Username already taken', false);
            }

            var newUser = new User();

            newUser.username = username;
            newUser.password = createHash(password)

            newUser.save(function(err, user){
                if(err){
                    return done(err, false);
                }
                console.log('Successfully signed up User ' + username);
                return done(null, newUser);
            });
        });
    })
);

    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    };

    var createHash = function(password){
        return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    };

};
1
There's a lack of good resources about implementing passport with a separate client and server fileezg

1 Answers

0
votes

The error is somewhere in your passport-init.js where you invoke done() with a string as a first argument, e.g. done('User not found', false)

What you want to do instead is throw an actual error:

done(new Error('User not found'), false);

and then handle it later. Once you find the error you can find the reason for redirect to (not) work.