那是我的代码: server.js:
require('dotenv').config()
var fs = require('fs')
var express = require('express')
var app = express()
var helmet = require('helmet')
var router = require('./router')
var session = require('express-session')
var passport = require('passport')
var cookie = require('cookie-parser')
var redis = require('redis').createClient(process.env.REDIS_PORT)
var redisStore = require('connect-redis')(session)
app.use(helmet())
app.use(cookie())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(passport.initialize())
app.use(passport.session())
app.use(session({
store: new redisStore({client: redis}),
secret: 'rior124jybtyokipoev5432rtoe34wpta',
cookie: {
path: '/',
httpOnly: true,
maxAge: 1000*60*60*24*365,
secure: false
},
resave: false,
saveUninitialized: false
}))
app.use(router)
require('./config/passport');
app.listen(process.env._PORT, () => {
console.log('[Info][Backend] Backend http serve succesfuly started! Port: '+process.env._PORT);
})
router / index.js:
var router = require('express').Router()
var auth = require('../lib/auth_mw')
var fs = require('fs')
router.use(require('./logging'))
router.use(require('./news'))
router.get('/', (req, res) => {
res.contentType('text/plain')
res.end(fs.readFileSync(__dirname+'/../siteinfo.txt'))
})
router.get('/private', auth, (req, res) => {
res.end('private')
})
module.exports = router
config / passport.js:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
var users = require('../models').users
passport.serializeUser(function(user, done) {
console.log('serialize: ', user);
done(null, user.email);
});
passport.deserializeUser(function(email, done) {
console.log('deserialize: ', email);
users.findOne({
attributes: [
'email'
],
where: {
email
}
}).then(user => {
done(null, user.email === email ? user.dataValues : false);
})
});
passport.use('local',
new LocalStrategy({ usernameField: 'email' }, async function(
email,
password,
done
) {
let user = await users.findOne({
attributes: [
'email',
'password'
],
where: {
email,
password
}
})
if (user.dataValues.email) {
return done(null, user.dataValues);
} else {
return done(null, false);
}
})
);
登录总是成功,但是当我尝试转到/ private时,不会调用反序列化功能!我在网上发现了许多解决方法,但无济于事。请提出您所建议的解决方案
P.S。我将sequelize用作数据库驱动程序(idk也许很重要)
答案 0 :(得分:0)
此查询将返回正确的用户,因此您无需再次检查输出。
users.findOne({
attributes: [
'email'
],
where: {
email
}
})
尝试用done(null, user.dataValues);
代替done(null, user.email === email ? user.dataValues : false);