Skip to content

Commit

Permalink
[backend] Improved IP Address resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
MananGandhi1810 committed Jan 12, 2025
1 parent 7b32af1 commit 75618c6
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
8 changes: 6 additions & 2 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
7 changes: 2 additions & 5 deletions backend/middlewares/rate-limit.js
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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);
Expand Down
7 changes: 7 additions & 0 deletions backend/utils/ip-addr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const getIp = (req) =>
req.headers["x-forwarded-for"] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;

export { getIp };

0 comments on commit 75618c6

Please sign in to comment.