// routes/front/login.js
import express from "express"
const loginRouter = express.Router()
import login from '../../controllers/front/login.js'

loginRouter.get('/',async (req,res)=>{
    if(req.session.user){
        res.redirect('/admin/post')
    }else{
        login.getItem(req,res)
    }
})

loginRouter.post('/',async (req,res)=>{
    login.checkUser(req,res)
})

export default loginRouter

 

// controllers/front/login.js
import config from "../../config.js"
import bcrypt from 'bcryptjs'
import userdb from "../../models/user.js"

class Login{
    async getItem(req,res){
        this.config = await config()
        this.config.pageTitle = 'ផ្ទៀងផ្ទាត់​ពាក្យ​សំងាត់'
        this.config.route = '/login'

        res.render('base',{data:this.config})
    }

    async checkUser(req,res){
        this.config = await config()
        this.config.pageTitle = 'ផ្ទៀង​ផ្ទាត់​ពាក្យ​សំងាត់'
        
        let user = await userdb.checkUser(req)
      
        if(user){
            if(bcrypt.compareSync(req.body.password, user.password)){
                req.session.user = user
                res.redirect('/admin/post')
            }else{
                this.config.message = 'ពាក្យ​សំងាត់​មិន​ត្រឹមត្រូវ​ទេ'
                this.config.route = '/login'
                res.render('base',{data:this.config})
            }
        }else{
            this.config.message = 'Email មិន​ត្រឹមត្រូវទេ'
            this.config.route = '/login'
            res.render('base',{data:this.config})
        }

    }
}

export default new Login()

 

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

export default new User()

 

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