1. Routes
-- Để kiểm tra đăng nhập với mọi Request, cho middleware lên đầu.
-- Thêm middleware vào mỗi router, giả sử muốn vào trang ad bắt buộc đăng nhập
-- Tại file: ./src/routes/router.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const express = require('express'); const router = express.Router(); const accountRouter = require('./accountRouter'); const adminRouter = require('./adminRouter'); const authen = require('../app/middlewares/authentication'); router.use(authen.getUser); router.use('/account', accountRouter); router.use('/admin', authen.requireLogin, adminRouter); router.use('/', (req, res) => { res.render('home/index'); }); module.exports = router; |
2. Middleware
-- Tạo file: ./src/app/middlewares/authentication.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
const jwt = require('jsonwebtoken'); const mongoDB = require('../../config/database/mongoDB'); const ObjectId = require('mongodb').ObjectId; module.exports = { getUser: async function (req, res, next) { if (!req.signedCookies.accountID) { res.locals.account = {}; return next(); } try { let token = req.signedCookies.accountID, decode = jwt.verify(token, process.env.SECRET_JWT), accountID = decode._id; let collection = mongoDB.getDB().collection('accounts'), account = await collection.findOne({ _id: new ObjectId(accountID) }); if (!account) { res.clearCookie('accountID'); res.locals.account = {}; } else { res.locals.account = account; } return next(); } catch (err) { res.clearCookie('accountID'); res.locals.account = {}; return next(); } }, requireLogin: function(req, res, next) { if (!res.locals.account.Gmail) { return res.redirect('/account/login'); } return next(); }, }; |
3. Tại view EJS
-- Dùng if else để check đăng nhập chưa rất dễ dàng
1 2 3 4 5 6 7 8 |
<div id="info-user"> <% if (locals.account.Gmail) { %> <%= locals.account.Gmail %> <a href="/account/logout">Logout</a> <% } else { %> <a href="/account/login">Đăng nhập</a> <% } %> </div> |
4. Tại Controller
-- Thêm điều kiện của res.locals vào mỗi Query sẽ được kết quả mong muốn :v
1 2 3 4 5 6 7 8 9 |
findListExist = (req, res, next) => { let conditions = { ManagerID: res.locals.account.ManagerID, removedAt: 0, }; Collection.find(conditions) .then((results) => res.json({ data: results })) .catch((err) => next()); }; |