Added middleware

feature/middleware
Arkadyuti Sarkar 2024-07-26 20:12:40 +05:30
parent 502f14336b
commit 50e0fa3c71
4 changed files with 47 additions and 1 deletions

3
.gitignore vendored
View File

@ -3,4 +3,5 @@ logs
.idea
build/Release
dist
node_modules
node_modules
yarn.lock

View File

@ -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",

View File

@ -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());

View File

@ -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();
};