// 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 userdb from '../../models/user.js'

class User{
    async getItem(req,res){
        this.config = await config()
        this.config.pageTitle = 'ទំព័រ​អ្នក​ប្រើប្រាស់'
        this.config.user = req.session.user

        if(this.config.user.role in {'Admin':1,'Editor':1}){
            this.config.route = '/admin/user'
            this.config.type = 'user'

        }else if(this.config.user.role === 'Author'){
            this.config.item = userdb.editItem(req)
        }

        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 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)
    }
}

export default new User()

 

Heroku: https://khmerweb-sale.herokuapp.com/login