The shop's login already has a per-IP limit: after 5 failed logins from one address, that address gets 429. An attacker with many addresses gets around it by sending each guess from a new one, so no address ever reaches 5. What the attacker gets: they can guess one customer's password for as long as it takes, and they're in the moment a guess is right.
The fix counts failures per account as well. After 5 failed logins on one email, wherever they came from, the account is locked for 15 minutes: you keep the second the lock ends and refuse every login on that email until then, even one with the right password. A lock time is just "now plus a duration", compared with <. Here is the same idea for a sign-in code that stays valid for 10 minutes:
CODE_VALID_UNTIL = {}
def send_code(email):
CODE_VALID_UNTIL[email] = now() + 10 * 60
def code_still_valid(email):
return now() < CODE_VALID_UNTIL.get(email, 0)
A locked account answers exactly like a wrong password: 401 with "Wrong email or password". The attacker can't tell the lock from a miss, so even a right guess during the lock looks like every other failure. A successful login sets the account's count back to 0, so a few typos spread over months never add up to a lock.
The check sets the clock (now(), in seconds) and the address of each request:
POST /login ana, 5 wrong passwords from 5 addresses, t=1000 → 401 {"error": "Wrong email or password"} (each)
POST /login ana, "sunflower-42", t=1100 → 401 {"error": "Wrong email or password"}
POST /login ben, "teapot-fan-22", t=1100 → 200 {"message": "Welcome back, ben@example.com"}
POST /login ana, "sunflower-42", t=1899 → 401 {"error": "Wrong email or password"}
POST /login ana, "sunflower-42", t=1900 → 200 {"message": "Welcome back, ana@example.com"}
Your task: add the dictionaries FAILS_BY_EMAIL and LOCKED_UNTIL. On every failed login, add 1 to the email's count; at 5, lock the email until now() + 15 * 60 and set its count back to 0. Before the password check, answer the usual 401 while the email is locked, and after a successful login set its count back to 0.
Assignment
Follow the Coding Tutorial to count failed logins per account, lock an account for 15 minutes after 5 of them, and answer a locked account exactly like a wrong password.
Hint
The lock check goes above the password check: a right password skips the failed-login block, so a check placed inside it would never stop one. Use LOCKED_UNTIL.get(email, 0) so an email that was never locked counts as unlocked.
Free plan: 30 tutor messages. PRO is unlimited.
