Account Recovery & Lockout — Auth

Forgot password: the reset link holds a random 32-byte token, the server stores only its SHA-256, it lives 60 minutes, it works once, and the /forgot-password…

Siti has forgotten her password. At the same time, in an internet cafe, someone is trying to guess Siti's password over and over. Both happen at the same login form, and this lesson deals with both.

Account recovery: Siti forgets her password, proves she owns the account through her email, then sets a new password. Lockout: after too many wrong passwords, the next attempts are held back for a while. Picture a school locker with a combination lock. Get the combination wrong five times and the locker refuses the next try for 15 minutes, not forever. If it locked forever, any prankster could make a friend's locker impossible to open. Forgot the combination? The caretaker gives the owner a one-time key, the combination is changed, and every old key stops working at once. In this picture, the locker is the account, the combination is the password, and the caretaker is the server. The one-time key is the reset token sent by email, and the old keys that stop working are the sessions that get revoked.

Forgot password: the flow

Here is the HTTP conversation in School Portal, exactly what the Lab shows (the token in the Lab is random):

POST /forgot-password HTTP/1.1
Host: portal.school.test

{"email": "[email protected]"}

HTTP/1.1 200 OK

{"message": "If that email is registered, a password reset link is on its way."}

POST /reset-password HTTP/1.1
Host: portal.school.test

{"token": "BIrrdlGOeVSVLLnsip3iOl4JlDLm9xGZVTNnygSkRCY", "email": "[email protected]", "password": "Grade11-Science2-safe"}

HTTP/1.1 200 OK

{"message": "Your password has been changed. Please log in again."}
  1. The reset token is made exactly the way the previous lesson, Magic Link Authentication, makes its token: 32 random bytes from crypto.getRandomValues, base64url in the email link, and only its SHA-256 is stored. The difference is its life: 60 minutes, because people need time to think of a new password.
  2. The answer to POST /forgot-password is always the same, registered email or not. A token that isn't found, was already used, or has expired gets 422 (the data sent can't be processed) with one message: "This reset link no longer works. Ask for a new one."

After the reset: revoke every session, tell the owner

This is what the server does when it receives POST /reset-password:

async function resetPassword(token, newPassword, now) {
  const row = resetTokens.get(await sha256Hex(token));
  if (!row || row.usedAt !== null || now >= row.expiresAt) return 422;
  row.usedAt = now; // single use
  const user = users.get(row.userId);
  user.passwordHash = await hashPassword(newPassword); // the Password Hashing lesson
  for (const [id, session] of sessions) {
    if (session.userId === user.id) sessions.delete(id); // every device logs out
  }
  sendEmail(user.email, "Your School Portal password was just changed. Not you? Contact the school admin.");
  return 200;
}

Lockout: a temporary pause per email and IP

The easiest approach is "5 wrong passwords and the account is locked until an admin opens it". It has a big problem: anyone who knows Siti's email can stop Siti from logging in, with nothing more than five wrong passwords. There are two fixes. First, the pause is temporary, not permanent. Second, only the pair of email and failing IP is held back, not the whole account. Compare:

Option What is held back When it opens
Permanent lock per account Siti's account, from anywhere when an admin opens it
Pause per email|IP only the pair of Siti's email and the failing IP on its own, 15 minutes after its failures

The server counts failures per counting key, a tag that identifies the sender: here the pair of email and IP. For example, from an internet cafe computer, someone types Siti's email with a wrong password five times. A minute later Siti logs in from home with the right password. With a pause per email|IP, five failures from the internet cafe only hold back the pair of Siti's email and the cafe's IP, [email protected]|198.51.100.23. Siti logs in from home (203.0.113.7) under a different counting key, its count is empty, so she can get in. With a permanent lock per account, Siti is locked out too, even with the right password.

This pause is throttling: slowing down, not locking. Someone who keeps switching IPs does get a fresh allowance of attempts on each IP. The next layers, a limit per IP and a captcha after a few failures, are in the Rate Limiting for Authentication lesson.

Sliding window: counting the failures of the last 15 minutes

This code records the time of each failure per counting key, and checks them before the password is checked:

const WINDOW = 15 * 60 * 1000;
const THRESHOLD = 5;
const failures = new Map(); // "email|ip" -> [failure time, ...]

function recordFailure(key, now) {
  if (!failures.has(key)) failures.set(key, []);
  failures.get(key).push(now);
}

function isLockedOut(key, now) {
  const recent = (failures.get(key) || []).filter((t) => t > now - WINDOW); // the last 15 minutes
  failures.set(key, recent); // old ones are dropped
  return recent.length >= THRESHOLD;
}

function clearFailures(key) {
  failures.delete(key); // called when a login succeeds
}

function login(email, password, ip, now) {
  const key = `${email.toLowerCase()}|${ip}`;
  if (isLockedOut(key, now)) return 429; // the password is not even checked
  if (!checkPassword(email, password)) {
    recordFailure(key, now); // recorded for any email, registered or not
    return 401;
  }
  clearFailures(key);
  return 200;
}

This is a trace from the Lab:

Time From What happens Failures in the last 15 minutes Answer
07:00 internet cafe wrong password number 1 to 5 1 to 5 401
07:01 internet cafe tries again 5 429, Retry-After: 840
07:02 Siti's home right password 0 (a different counting key) 200
07:15 internet cafe tries again 0, all of them have left the window the password is checked again

Retry-After: 840 means wait 840 seconds, that is 14 minutes, because the 07:00 failures leave the window at 07:15.

In the exercise the methods are named recordFailure(userId, now), isLockedOut(userId, now) and clearFailures(userId), with counting keys like 'u1', and time is a number of milliseconds. The counting key can be any string: in a real app it holds email|ip. The threshold is 5 and the window 15 * 60 * 1000.

Messages that give nothing away

Situation The same answer for everyone
Forgot password, registered email or not 200 "If that email is registered, a password reset link is on its way."
Failed login, wrong email or wrong password 401 "Email or password is wrong"
Too many failures 429 "Too many login attempts. Try again in 14 minutes."

An answer like "Email not registered" tells anyone which emails have a School Portal account. That is why the lockout is counted for unregistered emails as well. If 429 only appeared for accounts that exist, that 429 alone would show that the account exists.

In Laravel

In Laravel, forgot password, the reset and the login pause look like this:

// POST /forgot-password: one answer, whatever the status
Password::sendResetLink($request->only('email'));
return response()->json(['message' => 'If that email is registered, a password reset link is on its way.']);

// POST /reset-password
Password::reset($request->only('email', 'password', 'password_confirmation', 'token'), function (User $user, string $password) {
    $user->forceFill(['password' => Hash::make($password)])->setRememberToken(Str::random(60));
    $user->save();
    DB::table('sessions')->where('user_id', $user->id)->delete(); // every device logs out
    $user->notify(new PasswordChanged); // a Notification you write
});

// Login: a pause per email|IP
$key = Str::lower($request->input('email')).'|'.$request->ip();
if (RateLimiter::tooManyAttempts($key, 5)) {
    $seconds = RateLimiter::availableIn($key);
    throw ValidationException::withMessages(['email' => "Too many login attempts. Try again in {$seconds} seconds."])->status(429);
}
if (! Auth::attempt($request->only('email', 'password'))) {
    RateLimiter::hit($key, 15 * 60);
    throw ValidationException::withMessages(['email' => 'Email or password is wrong']);
}
RateLimiter::clear($key);

⚠️ What locks the owner out, or keeps the intruder in

TL;DR: Forgot password: the reset link holds a random 32-byte token, the server stores only its SHA-256, it lives 60 minutes, it works once, and the /forgot-password answer is the same for every email. After the reset: hash the new password, revoke every session of the user on every device, and send a notification email. Lockout (holding back logins after too many wrong passwords): don't lock an account permanently, because anyone could lock its owner out. Pause temporarily per email|IP pair with a sliding window (only the failures of the last 15 minutes count). 5 failures in the last 15 minutes means 429 with Retry-After (how many seconds to wait). Old failures leave on their own, and a successful login clears the count. The failed-login message is always the same: "Email or password is wrong". In Laravel: Password::sendResetLink, Password::reset, and RateLimiter::tooManyAttempts, hit, clear.

⚡ Forgot password: prove it through email

Meaning: Account recovery: Siti asks for a reset link, proves she owns the account through her email, then sets a new password. The reset token in that link is single use and short-lived, and the server stores only its hash, exactly like a magic link.

⚡ After the reset: revoke every session

Meaning: Changing the password alone doesn't sign out someone who already logged in with the old one, because their session is still valid. So after the reset, delete every one of Siti's sessions and email the owner, so she finds out right away if someone else did the reset.

⚡ A pause per email and IP, not a permanent lock

Guess first: the server holds back logins after five wrong passwords. From an internet cafe, someone types Siti's password wrong five times. A minute later Siti logs in from home with the right password. Can she get in?

Yes, when the failures are counted per email|IP pair: the internet cafe's failures only hold back the pair of Siti's email and the cafe's IP. With a permanent lock per account, Siti is locked out too, even with the right password.

⚡ A 15-minute sliding window

Write:

function isLockedOut(key, now) {
  const recent = (failures.get(key) || []).filter((t) => t > now - WINDOW); // the last 15 minutes
  failures.set(key, recent); // old ones are dropped
  return recent.length >= THRESHOLD;
}

Meaning: failures records the time of each failure per key, such as an email|ip pair. isLockedOut keeps only the failures of the last 15 minutes (WINDOW), then holds back the login once there are THRESHOLD (5) of them. Old failures leave on their own, so typos spread over a day never reach the limit that holds back the login. A fixed counter (a count that only goes up) never drops old failures.

What you will learn