我使用passportjs来管理登录,看起来没有调用序列化和反序列化函数。
var express = require('express'),
config = require('./config/conf'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('cookie-session'),
mongoose = require('mongoose'),
passport = require('./config/passport'),
auth = require('./config/auth'),
userAuth = require('./userAuth'),
appSetup = require('./appSetup'),
port = 3001,
api = require('./api'),
admin = require('./admin');
// Connect to mongodb
var connect = function () {
var options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.dbAddress, options);
};
connect();
appSetup();
mongoose.connection.on('error', console.log);
mongoose.connection.on('disconnected', connect);
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
keys: ['dfhdjf376gdhjgssjgsdfjdfgjdf', 'dkjjksdsdsdsd1d22sdsjksd', 'kjksdj665656kddfdffjkdf5skdj']
}))
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', userAuth(passport));
app.use('/api', auth.api, api);
app.use('/admin', auth.admin, admin);
app.use(express.static(__dirname + '/public'));
app.listen(port, function() {
console.log('listening on ' + port);
});
Passport配置文件
var passport = require('passport');
var LocalStrategy = require('passport-local');
var User = require('../models/user');
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log('in ser');
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log('in deser');
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({username: username}, function(err, user) {
if(err) return done(err);
if(!user) {
return done(null, false, { message: 'Could not find a user with that username or email'});
}
if(user.validPassword(password)) {
return done(null, user);
} else {
return done(null, false, { message: 'Incorrect Password' });
}
});
}));
module.exports = passport;
答案 0 :(得分:3)
将您的代码与passportjs.org上的示例进行比较,我发现您使用了
LocalStrategy = require('passport-local');
而他们使用:
LocalStrategy = require('passport-local').Strategy;
查看他们的示例