As always, before creating any user, we need to create a post request route connecting to a controller that in turn connects to a model to save user in MongoDB database. However, for password security, we can install bcrypt and use it to hash password. Doing so, no body can read user password, even Admin.
// route/admin/user.js
import express from 'express'
const userRoute = express.Router()
import user from '../../controller/admin/user.js'
userRoute.get('/',async (req,res)=>{
if(req.session.user){
user.getItem(req,res)
}else{
res.redirect('/login')
}
})
userRoute.post('/',async (req,res)=>{
if(req.session.user){
user.postItem(req,res)
}else{
res.redirect('/login')
}
})
export default userRoute
// controller/admin/user.js
import config from '../../config.js'
import userDB from '../../model/user.js'
class User{
constructor(){
(async ()=>{
this.config = await config()
})()
}
async getItem(req,res){
this.config.pageTitle = 'ទំព័រអ្នកប្រើប្រាស់'
this.config.route = '/admin/user'
this.config.type = 'user'
res.render('base',{data:this.config})
}
async postItem(req,res){
userDB.postItem(req,res)
res.redirect('/admin/user')
}
}
export default await new User()
// model/user.js
import bcrypt from 'bcryptjs'
class User{
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,
date: req.body.datetime,
role: req.body.category,
email: req.body.email,
password: hashPassword,
}
await req.mydb.collection("users").insertOne(newUser)
}
}
export default new User()