Skip to content

Commit

Permalink
throw if req.ip is undefined
Browse files Browse the repository at this point in the history
fixes #254 (well, not really, but at least makes it more obvious)
  • Loading branch information
nfriedly committed Oct 5, 2021
1 parent 0943049 commit 17135ea
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 9 deletions.
3 changes: 2 additions & 1 deletion .gitignore
@@ -1,3 +1,4 @@
/node_modules/
npm-debug.log
.idea/
.idea/
.vscode/
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -177,7 +177,7 @@ Defaults to `false`. Behavior and name will likely change in future releases.

Function used to generate keys.

Defaults to req.ip:
Defaults to req.ip, similar to this:

```js
function (req /*, res*/) {
Expand Down
5 changes: 5 additions & 0 deletions lib/express-rate-limit.js
Expand Up @@ -18,6 +18,11 @@ function RateLimit(options) {
skipSuccessfulRequests: false, // Do not count successful requests
// allows to create custom keys (by default user IP is used)
keyGenerator: function (req /*, res*/) {
if (!req.ip) {
throw new Error(
"express-rate-limit: req.ip is undefined - are you sure you're using express?"
);
}
return req.ip;
},
skip: function (/*req, res*/) {
Expand Down
21 changes: 14 additions & 7 deletions test/express-rate-limit-test.js
Expand Up @@ -4,6 +4,7 @@ const assert = require("assert");
const request = require("supertest");
const sinon = require("sinon");
const rateLimit = require("../lib/express-rate-limit.js");
const { promisify } = require("util");

// todo: look into using http://sinonjs.org/docs/#clock instead of actually letting the tests wait on setTimeouts

Expand Down Expand Up @@ -75,18 +76,24 @@ describe("express-rate-limit node module", () => {
};
}

it("should not allow the use of a store that is not valid", (done) => {
it("should not allow the use of a store that is not valid", async () => {
function InvalidStore() {}

try {
assert.throws(() => {
rateLimit({
store: new InvalidStore(),
});
} catch (e) {
return done();
}
}, /store/);
});

done(new Error("It allowed an invalid store"));
it("should error when req.ip is undefined", async () => {
const limiter = rateLimit({});
const { IncomingMessage, OutgoingMessage } = require("http");
await assert.rejects(
promisify(limiter)(new IncomingMessage(), new OutgoingMessage()),
/express/,
"Should error with a message about express"
);
});

it("should let the first request through", async () => {
Expand Down Expand Up @@ -476,7 +483,7 @@ describe("express-rate-limit node module", () => {
assert(store.decrement_was_called, "decrement was not called on the store");
});

it.only("should decrement hits with closed response and skipFailedRequests", async () => {
it("should decrement hits with closed response and skipFailedRequests", async () => {
clock.restore();

const store = new MockStore();
Expand Down

0 comments on commit 17135ea

Please sign in to comment.