//routes/admin/user.js
import express from 'express'
const userRouter = express.Router()
import user from '../../controllers/admin/user.js'
userRouter.get('/',async (req,res)=>{
if(req.session.user){
user.getItem(req,res)
}else{
res.redirect('/login')
}
})
userRouter.post('/',async (req,res)=>{
if(req.session.user){
user.postItem(req,res)
}else{
res.redirect('/login')
}
})
export default userRouter
// controllers/admin/user.js
import config from "../../config.js"
import user from "../../models/user.js"
import userdb from '../../models/user.js'
class User{
async getItem(req,res){
this.config = await config()
this.config.pageTitle = 'ទំព័រអ្នកប្រើប្រាស់'
this.config.user = req.session.user
this.config.route = '/admin/user'
if(this.config.user.role in {'Admin':1,'Editor':1}){
this.config.type = 'user'
this.config.count = await userdb.count(req)
this.config.items = await userdb.getItem(req,this.config.maxPosts)
}else if(this.config.user.role === 'Author'){
this.config.item = await userdb.editItem(req,this.config.user.id)
}
res.render('base',{data:this.config})
}
async postItem(req,res){
await userdb.postItem(req)
res.redirect('/admin/user')
}
}
export default new User()
// 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)
}
async count(req){
return await req.mydb.collection('users').countDocuments()
}
async postItem(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
const hashPassword = bcrypt.hashSync(req.body.password, 12)
let newUser = {
id: id,
title: req.body.title,
content: req.body.content,
thumb: req.body.thumb,
postdate: req.body.datetime,
role: req.body.category,
email: req.body.email,
password: hashPassword,
}
await req.mydb.collection("users").insertOne(newUser)
}
async getItem(req,amount){
return await req.mydb.collection("users").find().sort({date:-1,_id:-1}).limit(amount).toArray()
}
async editItem(req,id){
return await req.mydb.collection('users').findOne({id:id})
}
}
export default new User()