// routes/front/login.js
import express from "express"
const loginRouter = express.Router()
import login from '../../controllers/front/login.js'
loginRouter.get('/',async (req,res)=>{
if(req.session.user){
res.redirect('/admin/post')
}else{
login.getItem(req,res)
}
})
loginRouter.post('/',async (req,res)=>{
login.checkUser(req,res)
})
export default loginRouter
// controllers/front/login.js
import config from "../../config.js"
import bcrypt from 'bcryptjs'
import userdb from "../../models/user.js"
class Login{
async getItem(req,res){
this.config = await config()
this.config.pageTitle = 'ផ្ទៀងផ្ទាត់ពាក្យសំងាត់'
this.config.route = '/login'
res.render('base',{data:this.config})
}
async checkUser(req,res){
this.config = await config()
this.config.pageTitle = 'ផ្ទៀងផ្ទាត់ពាក្យសំងាត់'
let user = await userdb.checkUser(req)
if(user){
if(bcrypt.compareSync(req.body.password, user.password)){
req.session.user = user
res.redirect('/admin/post')
}else{
this.config.message = 'ពាក្យសំងាត់មិនត្រឹមត្រូវទេ'
this.config.route = '/login'
res.render('base',{data:this.config})
}
}else{
this.config.message = 'Email មិនត្រឹមត្រូវទេ'
this.config.route = '/login'
res.render('base',{data:this.config})
}
}
}
export default new Login()
// models/user.js
// npm install bcryptjs
import bcrypt from 'bcryptjs'
class User{
async checkUser(req){
const query = {email:req.body.email}
return await req.mydb.collection("users").findOne(query)
}
}
export default new User()