From 75618c611d979d1419404325e65b02073dd13f2a Mon Sep 17 00:00:00 2001 From: Manan Gandhi Date: Sun, 12 Jan 2025 15:47:25 +0530 Subject: [PATCH] [backend] Improved IP Address resolution --- backend/index.js | 8 ++++++-- backend/middlewares/rate-limit.js | 7 ++----- backend/utils/ip-addr.js | 7 +++++++ 3 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 backend/utils/ip-addr.js diff --git a/backend/index.js b/backend/index.js index 5ba077f..3003d42 100644 --- a/backend/index.js +++ b/backend/index.js @@ -8,16 +8,20 @@ import userRouter from "./router/user.js"; import editorialsRouter from "./router/editorial.js"; import logger from "morgan"; import morgan from "morgan"; +import { getIp } from "./utils/ip-addr.js"; const app = express(); -morgan.token("user-id", (req, res) => { +morgan.token("user-id", (req, _) => { return req.user != undefined ? req.user.id : "Unauthenticated"; }); +morgan.token("ip", (req, _) => { + return getIp(req); +}); app.enable("trust proxy"); app.use( logger( - `[:date[web]] :remote-addr - ":method :url HTTP/:http-version" :status ":referrer" ":user-agent" User::user-id - :response-time ms`, + `[:date[web]] :ip - ":method :url HTTP/:http-version" :status ":referrer" ":user-agent" User::user-id - :response-time ms`, ), ); app.use(express.json()); diff --git a/backend/middlewares/rate-limit.js b/backend/middlewares/rate-limit.js index 56f1b88..60fd0f2 100644 --- a/backend/middlewares/rate-limit.js +++ b/backend/middlewares/rate-limit.js @@ -1,4 +1,5 @@ import { createClient } from "redis"; +import { getIp } from "../utils/ip-addr.js"; const redis = createClient({ url: process.env.REDIS_URL }); redis.connect(); @@ -8,11 +9,7 @@ const rateLimit = async (req, res, next, limit = 5, use = "") => { if (req.user) { key = req.user.id; } else { - key = - req.headers["x-forwarded-for"] || - req.connection.remoteAddress || - req.socket.remoteAddress || - req.connection.socket.remoteAddress; + key = getIp(req); } const redisId = `rate-limit:${use}/${key}`; const requests = await redis.incr(redisId); diff --git a/backend/utils/ip-addr.js b/backend/utils/ip-addr.js new file mode 100644 index 0000000..2b21c30 --- /dev/null +++ b/backend/utils/ip-addr.js @@ -0,0 +1,7 @@ +const getIp = (req) => + req.headers["x-forwarded-for"] || + req.connection.remoteAddress || + req.socket.remoteAddress || + req.connection.socket.remoteAddress; + +export { getIp };