//routes/admin/user.js
import express from 'express'
const routeUser = express.Router()

routeUser.get('/',async function(req,res){
    if(req.session.user){
        const module = await import('../../controllers/admin/user/read.js')
        module.default(req,res)
    }else{
        res.redirect('/admin/login')
    }
})

routeUser.post('/',async function(req,res){
    if(req.session.user){
        const module = await import('../../controllers/admin/user/create.js')
        module.default(req,res)
    }else{
        res.redirect('/admin/login')
    }
})

export default routeUser

 

//controllers/admin/user/create.js
import create from '../../../models/user/create.js'

export default async (req,res)=>{
    if(req.session.user.role === 'Admin'){
        await create(req)
    }

    res.redirect('/admin/user')
}

 

//models/user/create.js
//npm install bcryptjs
import bcrypt from 'bcryptjs'

export default async (req)=>{
    const id = Date.now() + Math.round(Math.random() * 1E9).toString()
    const hashPassword = bcrypt.hashSync(req.body.password, 12)

    let myobj = {
        userid: id, 
        title: req.body.title,
        password: hashPassword,
        email: req.body.email,
        role: req.body.category,
        thumb: req.body.thumb,
        info: req.body.content,
        video: req.body.entires,
        date: new Date(req.body.datetime)
    }

    await req.mydb.collection("users").insertOne(myobj)
}

 

GitHub: https://github.com/Sokhavuth/Blog_

Vercel: https://khmerweb-blog.vercel.app/