The shop moved to scrypt, but accounts made before the move still have a plain SHA-256 hash. check_password already knows both formats: a stored text that starts with scrypt: is checked with scrypt, anything else the old way. So old accounts can log in, but their hashes stay weak.
The attack: a thief who copies the users table looks the old SHA-256 hashes up in a list of common passwords and gets Ana's sunshine and Ben's letmein in a moment.
The fix: you can't convert the old hashes yourself, because a hash can't be turned back into the password. But at a successful login the server holds the plain password for a moment: right after the check passes, hash it with scrypt and store that in the old hash's place. Telling the two formats apart takes one startswith:
"5e884898da28…".startswith("scrypt:") # False: an old SHA-256 hash
"scrypt:16384:8:1:5d8e2f0a…".startswith("scrypt:") # True: already scrypt
The hidden check GET /check/stored shows each account's format, whether a common-password table cracks it, and whether its stored hash changed since the last look:
GET /check/stored → 200 [{"email": "ana@example.com", "settings": "sha256 (old)", "cracked": "sunshine", "changed": false}, …]
POST /login {"email": "ana@example.com", "password": "sunshine"} → 200 {"email": "ana@example.com"}
GET /check/stored → 200 [{"email": "ana@example.com", "settings": "scrypt:16384:8:1", "cracked": null, "changed": true}, …]
POST /login {"email": "ana@example.com", "password": "sunshine"} → 200 {"email": "ana@example.com"}
POST /login {"email": "ben@example.com", "password": "password"} → 401 {"error": "Wrong email or password"}
GET /check/stored → 200 [{"email": "ana@example.com", "settings": "scrypt:16384:8:1", "cracked": null, "changed": false}, {"email": "ben@example.com", "settings": "sha256 (old)", "cracked": "letmein", "changed": false}, …]
Your task: in login, after the password check and above the last return, add an if for a stored hash that doesn't start with "scrypt:". Inside it, make a new hash with hash_password from the password just sent, update the user's row by id, and commit.
Assignment
Follow the Coding Tutorial to replace an old SHA-256 hash with a scrypt hash at a successful login.
Hint
Put the upgrade after the password check, never before it: otherwise anyone could set a new password by logging in with a wrong one. Without db.commit() the new hash is never saved.
Free plan: 30 tutor messages. PRO is unlimited.
