我正在开发一个简单的社交网络,我希望用户通过passport.js在本地注册和登录。我正在关注this教程,所有代码都运行没有错误。但是,当我尝试登录时,用户通过了身份验证,但在索引路由上打印req.session
时却没有保持会话状态。这是我的护照配置文件:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../server/models/User.js');
module.exports = function(passport){
passport.serializeUser(function(user, done){
console.log('Serialized');
done(null, user._id);
});
passport.deserializeUser(function(id, done){
console.log('Deserialized');
User.findOne({id:id}, function(err, user){
done(err, user);
});
});
passport.use('local-login', new LocalStrategy({
usernameField:'email',
passwordField:'password',
passReqToCallback:true
},function(req, email, password, done){
console.log('Started');
User.findOne({email:email}, function(err, user){
console.log('Find query');
if(err){
console.log('Error occured');
console.error(err);
return done(err);
}
console.log('No error');
if(!user)return done(null, false, req.flash('loginMessage', 'No user with this email found'));
console.log('Got user', user);
if(!user.validatePassword(password, user.password)){
console.log('Not valid suka');
return done(null, false, req.flash('loginMessage', 'Wrong password!'));
}
console.log('Valid pass');
return done(null, user);
});
}));
}
这是我的server.js文件:
//Dependencies
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const path = require('path');
const morgan = require('morgan');
const mongoose = require('mongoose');
//Mongo setup
var mongoPath = 'mongodb://localhost:27017/party-net';
mongoose.connect(mongoPath, function(){
console.log('Party-net database connected');
});
//Passport
require('./config/passport.js')(passport);
//Application setup
var app = express();
//Static files
app.use('/views', express.static(path.join(__dirname, 'public', 'views')));
app.use('/scripts', express.static(path.join(__dirname, 'public', 'scripts')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
//Middleware setup
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(session({secret:'muchsecretinfomustkipithir', saveUninitialized:true, resave:true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//Routes
const index = require('./server/routes/index.js')(app, passport);
const api = require('./server/routes/api.js')(app, passport);
app.listen(8080, function(){
console.log('Server listening on port 8080');
});
登录路线代码:
app.post('/api/login', passport.authenticate('local-login', {
failureRedirect:'/'
}), (req, res) => {
console.log('Login route', req.isAuthenticated(), req.session);
//res.sendStatus(200);
res.redirect('/');
//res.redirect('/'+req.user.name+'/'+req.user.lastname);
});
最后索引路线代码:
app.get('/:firstname/:lastname', isLoggedIn , (req, res) => {
console.log('Requested', req.user, req.isAuthenticated());
res.send('Logged in successfully ' + req.params.firstname + ' ' + req.params.lastname);
});
答案 0 :(得分:2)
可能护照无法按照您使用的方式反序列化用户:User.findOne({id: id}, ...
,但按user._id
序列化,因此您应该使用:
User.findOne({ _id: id }, ...
或findById方法:
User.findById(id, function(err, user) { ...
答案 1 :(得分:0)
尝试
app.use(session({ 机密:“ 123”, 重新保存:是的, saveUninitialized:是的, Cookie:{maxAge:60 * 60 * 24 * 1000} }));