`
//logout
router.get("/logout", (req, res) => {
res.render("logout")
req.session.username = undefined
req.session.loggedIn = false
})
//login
router.get("/login", (req, res) => {
res.render("login")
})
router.post("/login", (req, res) => {
let data = JSON.parse(fs.readFileSync("./data.json"))
let exists = false
data.users.forEach(user => {
if(user.name === req.body.username){
exists = true
if(user.password === req.body.password){
req.session.loggedIn = true
req.session.username = user.name
res.redirect("/")
}else res.send("Incorrect password!")
}
})
if(exists === false){
res.send("There is no account with that username.")
}
})
//register
router.get("/register", (req, res) => {
res.render("register")
})
router.post("/register", (req, res) => {
let data = JSON.parse(fs.readFileSync("./data.json"))
let exists = false
data.users.forEach(user => {
if(user.name === req.body.username){
res.send("Please choose a different username!")
exists = true
}
})
if(exists === false){
let template = {
name: req.body.username,
password: req.body.password
}
data.users.push(template)
fs.writeFileSync("./data.json", JSON.stringify(data, null, 2))
res.send("Registered successfully!")
}
})
//home
router.get("/", (req, res) => {
console.log(req.session.loggedIn)
if(req.session.loggedIn === true){
res.render("index", {name: req.session.username})
}else res.render("index", {name: "Guest"})
})
` So, this is my code. I want to code a login/register/home/logout system but I have a little problem here. When I first load the home page it says that i'm logged in as guest(as it should). After I logged in it displays my username(as it should too). But when I logout and console.log the loggedIn variable it says false and at the home page true again. There it still displays my username. The loggedIn variable should be false at the home page. Can anyone help me?
I expect the variable to be false at the home page when I logout. I tried to change the order of the functions but nothing helped.
CodePudding user response:
You need to destroy the session
req.session.destroy();