const express = require('express')
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const bodyParser = require('body-parser')
const pug = require('pug')
const app = express()
app.set('views', './views')
app.set('view engine', 'pug')
app.use(session({
store: new FileStore(),
secret: 'wefjwoefkwlefmwlkm',
resave: false,
saveUninitialized: true,
}))
app.use(bodyParser.urlencoded({ extended: false }))
const userDB = {
findUser: function(id,password){
if (!this.allUsers[id] || this.allUsers[id]['password'] != password) {
return false
} else {
return true
}
},
allUsers: {
admin: {
password: '123'
},
nersery: {
password: '123123'
},
lionking: {
password: '123'
}
}
}
app.get('/login', (req, res) => {
if (req.session.userInfo) {
res.redirect('/welcome')
} else {
errorMessage = req.session.err
res.render('login',{errorMessage: errorMessage})
}
})
app.post('/login', (req, res) => {
const userId = req.body.userId
const userPassword = req.body.userPassword
if (userDB.findUser(userId,userPassword)) {
delete req.session.err
req.session.userInfo = {
id: userId
}
res.redirect('/welcome')
} else {
req.session.err = 'Check your id or password'
res.redirect('/login')
}
})
app.get('/logout', (req, res) => {
delete req.session.errorMessage
delete req.session.userInfo
res.redirect('/login')
})
app.get('/register', (req, res) => {
if (req.session.userInfo) {
res.redirect('/welcome')
} else if(req.session.errorMessage){
res.render('register',{errorMessage: req.session.errorMessage})
} else {
res.render('register')
}
})
app.post('/register', (req, res) => {
const userId = req.body.userId
const userPassword = req.body.userPassword
const userPasswordConfirm = req.body.userPasswordConfirm
if (userDB.allUsers[userId]) {
req.session.errorMessage = 'the id is already exist'
} else if(userPassword.length < 3){
req.session.errorMessage = 'your password should be more than 3 characters'
} else if(userPassword !== userPasswordConfirm){
req.session.errorMessage = 'Password is not correct with Password confirm'
} else {
delete req.session.errorMessage
userDB.allUsers[userId] = { password: userPassword}
req.session.userInfo = {id: userId}
req.session.save(() => {
res.redirect('/welcome')
})
}
res.redirect('/register')
})
app.get('/welcome', (req, res) => {
const userId = req.session.userInfo.id
res.render('welcome', {userId: userId})
})
app.listen(3000, () => {
console.log('Connected at 3000 port!')
})