Good afternoon, I'm having a little problem ... I made a simple login app using express and nodejs, it logs quietly and displaces, but when the user shifts and returns a page from the browser, do I redirect it to the login screen?
//Security middleware
app.use((req,res,next)=>{
console.log('login')
var path = parseurl(req).pathname
if(req.session){
if(req.session.userId){
var userId = req.session.userId
User.findOne({where:{id:userId}})
.then((usr)=>{
req.user = usr.dataValues
next()
})
.catch(err=>{
res.redirect('/error')
})
}else{
if(path != '/login' && path != '/error'){
res.redirect('/login')
}else{
next()
}
}
}else{
next()
}
})
app.get('/error',(req, res)=>{
res.send('Erro no banco de dados.')
})
app.get('/',(req, res, next)=>{
console.log(req.user)
if(req.user){
res.render('home',{user:req.user})
}else{
res.render('login')
}
})
app.get('/login',(req, res, next)=>{
if(req.user){
res.redirect('/')
}else{
res.render('login')
}
})
app.post('/login',(req, res, next)=>{
username = req.body.username
password = req.body.password
User.findOne({where:{username:username,password:password}})
.then( user =>{
if(user){
req.session.userId = user.id
res.redirect('/')
}else{
console.log('Usuário nao encontrado.')
res.redirect('/login')
}
})
.catch(err=>{
console.log("db error")
res.redirect('/error')
next()
})
})
app.get('/logout',(req,res, next)=>{
req.session.destroy(()=>{
res.redirect('/login')
})
})