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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| const Path2Regexp = require("path-to-regexp"); const { errcode, verifyToken } = require("../../utils/index");
function AuthenticationMiddleWare(pathObj = { }) { const includes = pathObj.includes; const excludes = pathObj.excludes; const [pathIncludesMap, pathExcludesMap] = [ { GET: {}, POST: {}, PUT: {}, DELETE: {}, OPTIONS: {} }, { GET: {}, POST: {}, PUT: {}, DELETE: {}, OPTIONS: {} } ]; Array.isArray(includes) ? includes.forEach(item => { const { method, path } = item; pathIncludesMap[method][Path2Regexp.pathToRegexp(path)] = Path2Regexp.pathToRegexp(path); }) : excludes && excludes.forEach(item => { const { method, path } = item; pathExcludesMap[method][Path2Regexp.pathToRegexp(path)] = Path2Regexp.pathToRegexp(path); }) ; const f = async (req, res, next) => { let needAuth = true; if (!pathExcludesMap && !pathIncludesMap) { needAuth = true; } else if (pathExcludesMap) { const pathList = pathExcludesMap[req.method]; for (const element in pathList) { if (pathList[element].test(req.url)) { needAuth = false; break; } } } else { needAuth = false; const pathList = pathIncludesMap[req.method]; for (const element in pathList) { if (element.test(req.url)) { needAuth = true; break; } } } if (needAuth) { const Authorization = req.headers.authorization; if (Authorization) { const token = Authorization.replace(/^Bearer /, ""); try { const decodeToken = await verifyToken(token); req.decodeToken = decodeToken; next(); } catch (error) { const { status, body } = errcode(40003); res.status(status); res.send(body); } } else { const { status, body } = errcode(40002); res.status(status); res.send(body); } } else { next(); } }; return f; }
module.exports = AuthenticationMiddleWare;
|