An Expiring Counter
Part of the Auth and Security section of Coddy's Node.js journey. Lesson 22 of 24.
A fixed window counts attempts from one starting time. Store since beside the count. For a one-minute window, it expires when now - since reaches 60000 milliseconds.
// A ten-second window in this example
if (now - since >= 10000) {
count = 0;
since = now;
}
count += 1;Within the window, keep its original start time. Moving it after every attempt would keep extending the wait. This practice supplies now so you can exercise the boundary without waiting. A running server obtains the current time from Date.now(). The login project uses the same { count, since } record.
Challenge
EasyUpdate a one-minute failure record in exercise.js. If now - since is at least 60000, start a new window at now with count 1. Otherwise increase the count and keep since. Return both fields.
POST {"count":3,"since":0,"now":10000}: expect {"count":4,"since":0}. At now:60000, expect {"count":1,"since":60000}.
The initial GET /result uses the supplied example {"count": 2, "since": 1000, "now": 61000}. Use POST /result with a JSON body to try other inputs.
Try it yourself
export function exercise({ count, since, now }) {
return { count: count + 1, since };
}
All lessons in Auth and Security
Practice on your own: Express playground