19 October 2019

NodeJS ExpressJS: Authentication [EX-15]

Authentication 
/views/auth/login.pug
login.pug
extends ../layouts/common.pug 

block content
    if errors
        each error in errors
            .m-auto.col-6.alert.alert-danger=  error
    div(class="m-auto col-6")
        h1(class="text-center") Login
        form(action="" method="POST")
            div(class="form-group")
                label Email
                input(type="email" name="email" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Password
                input(type="password" name="password" class="form-control" placeholder="Enter password")
            button(type="submit" class="btn btn-success float-right") Login
/routes/auth.route.js
auth.route.js
const express =  require('express');
const router = express();

const constroller = require('../controller/auth.controller');
const validate = require('../validate/auth.validate');

router.get('/login', constroller.login);
router.post('/login', validate.postLogin, constroller.postLogin);
router.get('/logout', constroller.postLogout);

module.exports = router;
/validate/auth.validate.js
auth.validate.js
module.exports.postLogin = function(req, res, next) {
    const errors = [];
    if (!req.body.email) {
        errors.push('Email is required');
    }
    if (!req.body.password) {
        errors.push('Password is required');
    }
    if (errors.length > 0) {
        res.render('auth/login', {
            errors: errors
        });
        return;
    }
    next();
}
/controller/auth.controller.js
auth.controller.js
const db = require('../db/index').lowDB;

module.exports.login = function (req, res, next) {
    res.render('auth/login');
}

module.exports.postLogin = function (req, res, next) {
    const email = req.body.email;
    const password = req.body.password;

    const user = db.get('users').find({
        email: email
    }).value();

    if (!user) {
        res.render('auth/login', {
            errors: ['User does not exits'],
            values: res.body
        });
    }
    if (password != user.password) {
        res.render('auth/login', {
            errors: ['Wrong password'],
            values: res.body
        });
    }
    res.cookie('userId', user.id);
    res.redirect('/users');
}

module.exports.postLogout = function (req, res, next) {
    res.clearCookie("userId");
    res.redirect('/');
}


CanAccep + Middlware
check login
/app.js
app.js
const express = require('express')
const app = express()
const port = 3000
const cookieParser = require('cookie-parser');

const userRoute = require('./routes').user;
const authRoute = require('./routes').auth;
const middlware = require('./middlwares/auth.middlware');

app.set('view engine', 'pug')
app.set('views', './views');

// https://expressjs.com/en/4x/api.html#req.body
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.use(cookieParser());
app.use(express.static('public'));

// GET method route
app.get('/', function (req, res) {
    res.render('index', {
        title: 'Hey',
        message: "ExpressJS"
    })
})

app.use('/users', middlware.authorize, userRoute);
app.use('/auth', authRoute);

app.listen(port, () => console.log(`Example app listening on port ${port}!`))
/middlwares/auth.middlware.js
auth.middlware.js
const db = require('../db/index').lowDB;

module.exports.authorize = function(req, res, next) {
    console.log(req.cookies); // const cookieParser = require('cookie-parser'); vs app.use(cookieParser());
    if (!req.cookies.userId) {
        res.redirect('auth/login')
        return;
    }
    const user = db.get('users').find({
        id: req.cookies.userId
    }).value();
    if (!user) {
        res.redirect('auth/login');
        return;
    }
    next();
}
Update Layout
/views/auth/login.pug
login.pug
extends ../layouts/common.pug 

block content
    if errors
        each error in errors
            .m-auto.col-6.alert.alert-danger=  error
    div(class="m-auto col-6")
        h1(class="text-center") Login
        form(action="" method="POST")
            div(class="form-group")
                label Email
                input(type="email" name="email" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Password
                input(type="password" name="password" class="form-control" placeholder="Enter password")
            button(type="submit" class="btn btn-success float-right") Login

/views/layouts/common.pug
2018
html
    head
        link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css")
        link(rel="stylesheet" href="/css/custom.css")
    body
        div(class="jumbotron text-center m-0 p-0")
            img(src="../../images/banner.jpg" class="w-100")
        nav(class="navbar navbar-expand-sm bg-dark navbar-dark")
            a(class="navbar-brand" href="/") Node JS + Express JS
            div(class="collapse navbar-collapse" id="collapsibleNavbar")
                ul(class="navbar-nav")
                    li(class="nav-item")
                        a(class="nav-link" href='/users') User Management
                    li(class="nav-item")
                        a(class="nav-link" href="/auth/login") Login
                    li(class="nav-item")
                        a(class="nav-link" href="/auth/logout") Logout
        div(class="container" style="margin-top:30px; min-height: 500px")
            div(class="row")
                div(class="col-sm-12")
                    block content
        div(class="jumbotron text-center p-3")
            h6 Copyright © 2019 Author DaiDH
/views/users/create.pug
create.pug
extends ../layouts/common.pug 

block content
    if errors
        each error in errors
             .m-auto.col-6.alert.alert-danger=  error

    h1(class="text-center") Create User
    form(action="/users/create" method="POST")
        div(class="col-6 m-auto")
            div(class="form-group")
                label Name
                input(name="name", type="text", autocomplete="off" class="form-control" placeholder="Enter name")
            div(class="form-group")
                label Address
                input(type="text" name="address" autocomplete="off" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Phone
                input(type="text" name="phone" autocomplete="off" class="form-control" placeholder="Enter phone")
            div(class="form-group")
                label Email
                input(type="email" name="email" autocomplete="off" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Password
                input(type="password" name="password" autocomplete="off" class="form-control" placeholder="Enter password")
            a(href="/users") 
                button(type="button" class="btn btn-info") << back
            button(type="submit" class="btn btn-success float-right") Create User
/views/users/view.pug
view.pug
extends ../layouts/common.pug 

block content
    div(class="col-6 m-auto")
        h1(class="text-center") View User Info
        div(class="form-group")
            label Name
            input(type="text", value= user.name, autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Addres
            input(type="text" value= user.address, autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Email
            input(type="text" value= user.email,  autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Phone
            input(type="text" value= user.phone, autocomplete="off" class="form-control" disabled)
        a(href="/users") 
            button(type="button" class="btn btn-info") << back
/views/users/index.pug
index.pug
extends ../layouts/common.pug 

block content
    h1(class="text-center") User Managerment
    a(href='/users/create') 
        Button(class="btn btn-info") Create User

    form(action = "/users/search/name", method="GET")
        div(class="input-group mb-3 col-4 float-right")
            input(name="name", type="text", autocomplete="off" class="form-control" placeholder="Enter search")
            div(class="input-group-append")
                button(class="btn btn-success") Search

    table(class="table table-hover")
        thead
            tr
                th(scope="col") Name
                th(scope="col") Address
                th(scope="col") Phone
                th(scope="col") Email
                th(scope="col") 
        tbody
            each user in users
                tr
                    th(scope="row")= user.name
                    td= user.address 
                    td= user.phone
                    td= user.email
                    td
                        a(class="float-right" href='users/'+ user.id) View
/views/index.pug
index.pug
extends ./layouts/common.pug 

block content
    h1= title
    h2= message

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang