无法在node.js中使用快速会话注销

时间:2019-05-27 06:39:27

标签: node.js mongodb express-session

我在我的node.js应用程序中使用express-session进行身份验证。登录路由工作正常,但我无法注销。单击注销链接后,会话将保留在我的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');
});

我希望会话被破坏,并且页面将被重定向到登录页面。谁能告诉我我在做什么错?

1 个答案:

答案 0 :(得分:0)

尝试

module.exports = (req, res) => {
  if(req.session) {
    req.session.cookie.maxAge = 0
    delete req.session
  }
  res.redirect('/auth/login')
}