Hey everyone, I'm currently dealing with an issue in my server.js
setup where I'm trying to display the message "logged out successfully" on the /login
page when a user logs out. The problem stems from using multiple middleware and feeling overwhelmed by it all. I've attempted to pass the message using res.locals, req.session, and req.session.flash, but it seems like some method or middleware is causing the sessions to be deleted.
I suspect something might be happening within the .delete()
method, as everything works fine when passing variables outside of that section. It's possible that the .delete() method or the method_override middleware has certain features I'm not aware of, or maybe I'm not using next() correctly. Any help would be greatly appreciated as I've already invested significant time into this.
On another note, if anyone knows how to check if I've been redirected to the /login
page, that could potentially lead me to some workarounds for the current issue. Additionally, are there better ways to pass messages? Should queries be used in this scenario? As a perfectionist, I'm not a fan of messy URLs :D
require('dotenv').config()
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const users = []
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')
const passport = require('passport')
const initializePassport = require('./passport-config')
initializePassport(passport,
email => users.find(user => user.email === email),
name => users.find(user => user.name === name))
app.set('view engine','ejs')
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.get('/login', checkNotAuthenticated, (req, res) => {
console.log(req.session.test)
res.render('login', { msg: req.flash('info')})
})
app.delete('/logout', (req, res) => {
req.logOut((err) => err ? next(err) : '')
req.flash('info', 'logged out successfully')
req.session.test = true;
res.redirect('/login')
})
function checkNotAuthenticated(req, res, next){
if(!req.isAuthenticated()){
return next()
}
res.redirect('/')
}