Skip to content

Commit a3f18d6

Browse files
committed
refactor: change limiter.Try() to .removeToken()
1 parent 7928dc2 commit a3f18d6

File tree

2 files changed

+10
-12
lines changed

2 files changed

+10
-12
lines changed

src/node/routes/login.ts

+3-6
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,8 @@ export class RateLimiter {
2121
return this.minuteLimiter.getTokensRemaining() > 0 || this.hourLimiter.getTokensRemaining() > 0
2222
}
2323

24-
public try(): boolean {
25-
if (this.canTry()) {
26-
return this.minuteLimiter.tryRemoveTokens(1) || this.hourLimiter.tryRemoveTokens(1)
27-
}
28-
return false
24+
public removeToken(): boolean {
25+
return this.minuteLimiter.tryRemoveTokens(1) || this.hourLimiter.tryRemoveTokens(1)
2926
}
3027
}
3128

@@ -91,7 +88,7 @@ router.post("/", async (req, res) => {
9188

9289
// Note: successful logins should not count against the RateLimiter
9390
// which is why this logic must come after the successful login logic
94-
if (!limiter.try()) {
91+
if (!limiter.removeToken()) {
9592
throw new Error("Login rate limited!")
9693
}
9794

test/unit/routes/login.test.ts

+7-6
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,20 @@ describe("login", () => {
44
describe("RateLimiter", () => {
55
it("should allow one try ", () => {
66
const limiter = new RateLimiter()
7-
expect(limiter.try()).toBe(true)
7+
expect(limiter.removeToken()).toBe(true)
88
})
99

1010
it("should pull tokens from both limiters (minute & hour)", () => {
1111
const limiter = new RateLimiter()
1212

1313
// Try twice, which pulls two from the minute bucket
14-
limiter.try()
15-
limiter.try()
14+
limiter.removeToken()
15+
limiter.removeToken()
1616

1717
// Check that we can still try
1818
// which should be true since there are 12 remaining in the hour bucket
1919
expect(limiter.canTry()).toBe(true)
20-
expect(limiter.try()).toBe(true)
20+
expect(limiter.removeToken()).toBe(true)
2121
})
2222

2323
it("should not allow more than 14 tries in less than an hour", () => {
@@ -27,10 +27,11 @@ describe("login", () => {
2727
// so if we run it 15 times, 14 should return true and the last
2828
// should return false
2929
for (let i = 1; i <= 14; i++) {
30-
expect(limiter.try()).toBe(true)
30+
expect(limiter.removeToken()).toBe(true)
3131
}
3232

33-
expect(limiter.try()).toBe(false)
33+
expect(limiter.canTry()).toBe(false)
34+
expect(limiter.removeToken()).toBe(false)
3435
})
3536
})
3637
})

0 commit comments

Comments
 (0)