refactor: update rateLimiter to check try

This changes adds a new method called `.canTry` to the rate limiter to check if
there are tokens remaining in the bucket.

It also adds suggestions from @oxy to make sure the user can brute force past
the rate limiter.
This commit is contained in:
Joe Previte 2021-04-16 14:22:09 -07:00
parent a8719e1f79
commit d8e45057c7
No known key found for this signature in database
GPG Key ID: 2C91590C6B742C24

View File

@ -17,11 +17,15 @@ export class RateLimiter {
private readonly minuteLimiter = new Limiter(2, "minute") private readonly minuteLimiter = new Limiter(2, "minute")
private readonly hourLimiter = new Limiter(12, "hour") private readonly hourLimiter = new Limiter(12, "hour")
public canTry(): boolean {
return this.minuteLimiter.getTokensRemaining() > 0 || this.hourLimiter.getTokensRemaining() > 0
}
public try(): boolean { public try(): boolean {
if (this.minuteLimiter.tryRemoveTokens(1)) { if (this.canTry()) {
return true return this.minuteLimiter.tryRemoveTokens(1) || this.hourLimiter.tryRemoveTokens(1)
} }
return this.hourLimiter.tryRemoveTokens(1) return false
} }
} }
@ -59,6 +63,11 @@ router.get("/", async (req, res) => {
router.post("/", async (req, res) => { router.post("/", async (req, res) => {
try { try {
// Check to see if they exceeded their login attempts
if (!limiter.canTry()) {
throw new Error("Login rate limited!")
}
if (!req.body.password) { if (!req.body.password) {
throw new Error("Missing password") throw new Error("Missing password")
} }