//routes/backend/login.js
import express from 'express'
const loginRouter = express.Router()
import login from '../../controllers/backend/login.js'
loginRouter.get('/',async function(req,res){
await login.getPage(req,res)
})
loginRouter.post('/',async function(req,res){
await login.verifyUser(req,res)
})
export default loginRouter
//controllers/backend/login.js
import user from '../../models/user.js'
import bcrypt from 'bcryptjs'
class Login{
async getPage(req,res){
if(req.session.user){
res.redirect('/admin/post')
}else{
req.settings.pageTitle = 'ទំព័រចុះឈ្មោះ'
req.settings.message = ''
req.settings.route = '/admin/login'
res.render('base', {data:req.settings})
}
}
async verifyUser(req,res){
let result = await user.checkUser(req,res)
if(result){
if(bcrypt.compareSync(req.body.password, result.password)){
req.session.user = result.id
res.redirect('/admin/post')
}else{
req.settings.message = 'ពាក្យសំងាត់មិនត្រឹមត្រូវទេ'
req.settings.route = '/admin/login'
res.render('base',{data:req.settings})
}
}else{
req.settings.message = 'Email មិនត្រឹមត្រូវទេ'
req.settings.route = '/admin/login'
res.render('base',{data:req.settings})
}
}
}
export default new Login()
//models/users.js
//npm install bcryptjs
import bcrypt from 'bcryptjs'
class User{
async createRootUser(req,res){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
const hashPassword = bcrypt.hashSync("xxxxxxxxxxxx", 8)
const user = {
id: id,
title: "Sokhavuth",
password: hashPassword,
email: 'xxxxxxxxxx',
role: 'Admin',
thumb: '',
info: '',
video: '',
date: new Date()
}
await req.mydb.collection("users").insertOne(user)
}
async checkUser(req,res){
const query = {email:req.body.email}
let user = await req.mydb.collection("users").findOne(query)
return user
}
}
export default new User()