Review request

Habit-tracking API built with FastAPI, does the auth flow hold up?

Solved · 319 viewsasked by kai_makes

Repo or live app

git.example.com/kaitanaka/habit-api ↗

Third app, first one with a real backend instead of just Supabase. ChatGPT walked me through JWT auth in FastAPI. It works end to end but I've never written auth myself before and I'd like someone who has to check I didn't skip a step.

Comment

2 answers

Marked as helpful by the asker
olu_backend

Structurally fine, one real issue: verify_token catches JWTError but not ExpiredSignatureError separately, so an expired token currently returns a 500 instead of a 401. Split the except:

except ExpiredSignatureError:
    raise HTTPException(401, "token expired")
except JWTError:
    raise HTTPException(401, "invalid token")

Also your refresh tokens don't have a revocation check, fine for now at this scale, just know it's there if you ever need to log someone out remotely.

Comment
Split the excepts, expired tokens return 401 now. kai_makes
grace_mw

Olu covered the token handling. The other half of auth is the login endpoint itself, and yours has no rate limit. I ran a quick loop against a local copy of the repo:

Two hundred wrong passwords, two hundred fast 401s, no slowdown. Anyone with a list of leaked passwords can try them against your users at full speed. Add a limiter keyed on email plus IP, something like five attempts per minute, and return 429 after that. slowapi does it in a few lines for FastAPI.

While you're in that file, check the passwords are hashed with bcrypt or argon2 (passlib's CryptContext), not sha256. ChatGPT tutorials go both ways.

Comment
Hashing is bcrypt, checked. The rate limit was missing, added slowapi with 5/minute on login. kai_makes
Nice. Rerun the same loop, you should see 429s after the fifth attempt. grace_mw
195 x 429. Never been this happy to see requests fail. kai_makes