Я использую экспресс-сессию в моем приложении node.js для аутентификации. Маршрут входа в систему работает нормально, но я не могу выйти. Сеанс остается там в моей базе данных mongodb с новым сроком действия при щелчке по ссылке выхода из системы.
Я пытался использовать req.session.destroy () и req.session.cookie.expires = new Date (). GetTime (), чтобы срок действия файла cookie истек при нажатии кнопки выхода, но ничего не получалось.
код экспресс-сессии в index.js
app.use(expressSession({
secret: 'secret',
cookie: { maxAge: 60 * 60 * 24 * 1000 }, //if maxAge is set to anything between 1000 and 9000 the logout button works
resave: false,
saveUninitialized: false,
store: new mongoStore({
mongooseConnection: mongoose.connection
})
}));
loginUser.js
const bcrypt = require('bcrypt')
const User = require('../database/models/User')
module.exports = (req, res) => {
const {
email,
password
} = req.body;
// try to find the user
User.findOne({
email
}, (error, user) => {
if (user) {
// compare passwords.
bcrypt.compare(password, user.password, (error, same) => {
if (same) {
req.session.userId = user._id
res.redirect('/')
} else {
res.redirect('/auth/login')
}
})
} else {
return res.redirect('/auth/login')
}
})
}
storeUser.js
const User = require('../database/models/User')
module.exports = (req, res) => {
User.create(req.body, (error, user) => {
if (error) {
const registrationErrors = Object.keys(error.errors).map(key => error.errors[key].message)
req.flash('registrationErrors', registrationErrors)
return res.redirect('/auth/register')
}
res.redirect('/')
})
}
auth.js
const User = require('../database/models/User')
module.exports = (req, res, next) => {
User.findById(req.session.userId, (error, user) => {
if (error || !user) {
return res.redirect('/')
}
next()
})
}
logout.js
module.exports = (req, res) => {
req.session.destroy(() => {
res.redirect('/auth/login');
});
Я ожидаю, что сессия будет разрушена, и страница будет перенаправлена на страницу входа. Может кто-нибудь сказать мне, что я делаю не так?