护照身份验证成功但不重定向并给出 500 错误

Passport Authentication success but does not redirect and gives 500 error

我正在通过制作像 Twitter 这样的社交媒体 Web 应用来学习 Mean Stack 但是在注册或登录时我获得了成功并且还在数据库中创建了一个用户但是页面没有重定向并给出错误 500

下面是代码

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 = 函数(护照){

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;

}

护照-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);
    };

};

错误出在您的 passport-init.js 中的某处,您在其中使用字符串作为第一个参数调用 done(),例如done('User not found', false)

您要做的是抛出实际错误:

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

以后再处理。找到错误后,您可以找到重定向到(不)工作的原因。