To get data from any form, we need to use urlencoded( ) middleware by adding the code below to the entry point.

 

app.use(express.urlencoded({extended:false}))

 

As the request from the login form is a post request, we could define a route for this request as ‘/login’ route for post request.

 

// route/login.js
import express from 'express'
const loginRoute = express.Router()

loginRoute.get('/login',async (req,res,next)=>{
    const module = await import('../controller/login/getLogin.js')
    module.default(req,res)
})

loginRoute.post('/login',async (req,res,next)=>{
    const module = await import('../controller/login/postLogin.js')
    module.default(req,res)
})

export default loginRoute

 

The controller to be called by the above route function is:

 

//controller/login/postLogin.js
import checkUser from '../../model/user/checkUser.js'
import bcrypt from 'bcryptjs'

export default async (req,res)=>{
    let module = await import('../../config.js')
    let setting = await module.default()

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

 

The model  to check if a user with the email from the login form exist or not is:

 

//model/user/checkUser.js

export default async (req)=>{
    const query = {email:req.body.email}
    let user = await req.mydb.collection("users").findOne(query)
    return user
}

 

If we enter the right email and password, we will be redirected to the dashboard through “/admin/job”  route that will be defined in the next lesson.

 

GitHub: https://github.com/Sokhavuth/khmerweb-job

Heroku: https://khmerweb-job.herokuapp.com