From 50e0fa3c71ee030c8b15771d5a9113e655cc066b Mon Sep 17 00:00:00 2001 From: Arkadyuti Sarkar Date: Fri, 26 Jul 2024 20:12:40 +0530 Subject: [PATCH] Added middleware --- .gitignore | 3 ++- package.json | 1 + src/index.js | 2 ++ src/utils/helpers.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ac59ccc..900c1a9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ logs .idea build/Release dist -node_modules \ No newline at end of file +node_modules +yarn.lock \ No newline at end of file diff --git a/package.json b/package.json index 5c59059..35a2b47 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "express-fileupload": "^1.0.0", "helmet": "^3.13.0", "jade": "~1.11.0", + "jsonwebtoken": "^9.0.2", "lodash": "^4.17.13", "moment": "^2.22.2", "morgan": "1.9.1", diff --git a/src/index.js b/src/index.js index d6ebff6..28883f0 100644 --- a/src/index.js +++ b/src/index.js @@ -10,6 +10,7 @@ import compression from "compression"; import fileUpload from "express-fileupload"; import routes from "./routes/index"; import {PORT} from "./config/constants"; +import { accessTokenMiddleWare } from "./utils/helpers"; var app = express(); @@ -35,6 +36,7 @@ app.use( }) ); +app.use(accessTokenMiddleWare) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); diff --git a/src/utils/helpers.js b/src/utils/helpers.js index 5f040ec..4e185ac 100644 --- a/src/utils/helpers.js +++ b/src/utils/helpers.js @@ -1,3 +1,6 @@ +const jwt = require('jsonwebtoken'); + + export const IsJsonString = str => { try { JSON.parse(str); @@ -17,3 +20,42 @@ export const invalidCustomParam = (req, res, paramater, message) => { } return false; }; + + +function decodeToken(authHeader) { + if (!authHeader) { + throw new Error('Authorization header is missing'); + } + + const token = authHeader.split(' ')[1]; + if (!token) { + throw new Error('Token is missing'); + } + + try { + const decoded = jwt.decode(token); + return decoded; + } catch (err) { + throw new Error('Failed to decode token'); + } +} + +export const accessTokenMiddleWare = (req, res, next) => { + /** + * Check here if private or public route + * if private route and req.headers.authorization is empty + * return res.status(401).send('Authorization header is missing'); + */ + if (!req.headers.authorization) { + next(); + return + } + const incomingToken = decodeToken(req.headers.authorization); + const {data} = incomingToken || {}; + + //TODO:: Manipulate the header/access token here + const customHeaderValue = 'CustomHeader-' + data + + res.setHeader('X-Custom-Header', customHeaderValue); + next(); +}; \ No newline at end of file