Start learning free

LESSON 95 OF 173 · BACKEND: USERS AND SECURITY

Too Many Tries: Rate Limits in Go

Practice

Right now POST /login answers every try. A script could send thousands of passwords for one email until one works. A rate limit stops it: the shop counts the failed logins of each email, and after 3 it answers 429 Too Many Requests without even checking the password.

Counting with a map: a map can hold a count per key. Reading a key that isn't there gives 0, the zero value of int, and ++ works on a map entry too. Here it counts the likes of each product:

var likes = map[int]int{}

app.HandleFunc("POST /products/{id}/like", func(w http.ResponseWriter, r *http.Request) {
    id, _ := strconv.Atoi(r.PathValue("id"))
    likes[id]++
    writeJSON(w, 200, map[string]int{"likes": likes[id]})
})

Three details make the limit work. The check comes first, before the password: once the count is 3, even the right password gets 429, so a guesser can't tell a right guess from a wrong one. Emails with no account are counted too, so the answers look the same whether the account exists or not. And a right password sets the count back to 0, so three typos spread over a year don't lock anyone out.

Ana's password is secret123. Your code must give these answers, in this order:

POST /login  {"email": "ana@example.com", "password": "guess1"}     →  401  {"error": "Wrong email or password"}
POST /login  {"email": "ana@example.com", "password": "guess2"}     →  401  {"error": "Wrong email or password"}
POST /login  {"email": "ana@example.com", "password": "secret123"}  →  200  {"token": "<token>"}
POST /login  "guess3", then "guess4", then "guess5"                  →  401  each time
POST /login  {"email": "ana@example.com", "password": "secret123"}  →  429  {"error": "Too many failed logins, try again later"}
POST /login  {"email": "admin@example.com", "password": "admin-pass-123"}  →  200  {"token": "<admin>"}
GET /me  (Bearer <token>)  →  200  {"email": "ana@example.com", "id": 2, "role": "customer"}

Your task: declare the package variable failedLogins, a map[string]int. In the POST /login handler, answer {"error": "Too many failed logins, try again later"} with 429 and stop when the email already has 3 or more failed tries. Add 1 to the email's count on every failed login, and set it back to 0 on a good one.


Assignment
Follow the Coding Tutorial to add a rate limit to POST /login: the counter, the 429 check and its return, counting failures and the reset.


Hint
Read a count with failedLogins[data["email"]]: an email that never failed isn't a key yet, so it reads 0. The 429 check goes right after the decode line, before the user is even looked up.


STEP 1 OF 6
    Ctrl + Enter to check

    Sec Rate Limit in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free