Exercise: Study Group Sign-In
Give a study group's FastAPI app accounts it can trust, with passwords saved only as Argon2 hashes from pwdlib, a sign-up that answers 201 or 409 for a used email, a sign-in at POST /auth/token that hands out a PyJWT token good for an hour or one vague 401, and a /me route that reads the token, all tested on a throwaway SQLite database.
Journeyman · FastAPI · REST API · Updated
Bright Minds Study Group is getting accounts. Its database, its data module and its error handlers are ready, the way Module 3 left Rep Counter. You'll write the part that keeps the students safe: passwords saved only as hashes, a sign-up that refuses a used email, a sign-in that hands out a token good for an hour, and a /me route that knows who's asking. Tests check every answer, look inside the database for the hashes, and look inside the tokens.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-study-group-sign-in, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-study-group-sign-in.git
Git makes a folder, exercise-fastapi-study-group-sign-in, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on. pwdlib, with Argon2, and PyJWT are in requirements.txt, and both install ready-made, so Windows needs no extra build tools. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.
The folder holds:
security.py: passwords and tokens, in plain Python:hash_password,check_password,make_tokenandstudent_id_from_token, and theSECRET_KEYline, all yours to write.routers/auth.py: the routes, for you to write. The models,SignUpandStudentOut, and the token reader,oauth2_scheme, are ready.students_data.py: every SQL statement:add_student(which raisesDuplicateEmailfor a used email),find_student_by_email(which includes the hash, for checking a sign-in) andget_student(which doesn't).database.py,migrations/0001_create_students.sqlandmain.py: the database file, the students table with itsUNIQUEemail, theget_dbdependency, and the app with the error handlers that give every error one shape.tests/test_auth.py: the tests. Each one gets a fresh database in pytest'stmp_pathwith two students, Maya and Theo, as Testing with a Real, Throwaway Database does. You don't need to change it.requirements.txtandpytest.ini: the packages, at exact versions, and where pytest finds the tests and your code.
What to do
The comment at the top of routers/auth.py lists every request, and the one at the top of security.py lists every function. The requests:
POST /auth/sign-up JSON {"name": "Priya", "email": "priya@example.com", "password": "lantern-quiet-river"}
201 {"id": 3, "name": "Priya", "email": "priya@example.com"}, her password saved only as its hash
409 for a used email: detail "That email already has an account."
POST /auth/token Form fields username (the email) and password
200 {"access_token": "<a JWT>", "token_type": "bearer"}, the JWT's payload
{"sub": "1", "exp": <an hour from now>} for Maya, signed with HS256 and JWT_SECRET
401 for a wrong email or a wrong password, the same for both: detail "The email or password is wrong."
GET /me Header Authorization: Bearer <the token>
200 {"id": 1, "name": "Maya", "email": "maya@example.com"}
401 with no header: detail "Not authenticated"
401 for a token that's expired, signed with another key or not a token, or a student who's gone:
detail "The token isn't valid or has expired."
Every 401 sends the header WWW-Authenticate: Bearer
- Write
security.py. ReadSECRET_KEYfrom the environment variableJWT_SECRET. Thenhash_passwordandcheck_passwordwith pwdlib, andmake_tokenandstudent_id_from_tokenwith PyJWT, as the comment at the top describes. - Sign up with
POST /auth/sign-up: hash the password, save the student, answer 201 withStudentOut, and turnDuplicateEmailinto a 409. - Sign in with
POST /auth/token: takeOAuth2PasswordRequestForm, check the password, and answer the token, or the 401 with its header. - Answer
GET /mewith the student the token names, or the 401 with its header.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
No server needs to be running, and the tests give the app a test value of JWT_SECRET themselves. At first all 14 tests fail: none of the routes exists yet. Each part you finish turns its tests green. A failing test's message says what it sent, what it expected and what came back, for example POST /auth/token for Maya with a wrong password should answer 401, but it answered 404 with {"status":404,"title":"Not Found","detail":"Not Found"}.
To try it yourself, the app needs its own key first. The README shows the two lines that make a random one with Python's secrets module and start the app, then how to sign up, click Authorize on the docs page at http://127.0.0.1:8000/docs, and try GET /me as the student you made.
Hints
- Start with
security.py.hash_passwordandcheck_passwordare one line each:password_hash.hash(password)andpassword_hash.verify(password, hashed). make_tokenis the one from Tokens: Signing In with a JWT, withtimedelta(minutes=TOKEN_MINUTES). PyJWT wantssubas text, so it'sstr(student_id)going in andint(payload["sub"])coming out.student_id_from_tokenputsjwt.decodein atry.except jwt.InvalidTokenError:catches an expired token, another key's signature and text that isn't a token, all at once: returnNone.- Sign-up answers without the password.
response_model=StudentOutsends onlyid,nameandemail, andstudents_data.get_student(conn, student_id)gives exactly those for the new student. - Every 401 is the same
HTTPException, withheaders={"WWW-Authenticate": "Bearer"}. A small function that makes it, given the detail, saves writing it three times. The handler inmain.pypasses the header on in the one error shape. - In
GET /me, a bad token givesNonefromstudent_id_from_token, and a deleted student givesNonefromget_student. Oneif student is None:answers both.
When you're done
Every test is green: pytest's last line says 14 passed. And on the docs page, with your own key set, sign up a student, click Authorize with their email and password, and GET /me answers with that student, with no password and no hash anywhere in the answer.
Now look at a token your app made. Paste it into the Do It's read_payload from Tokens: Signing In with a JWT, or read its middle part in your head. What could a stranger who found it learn, and what couldn't they do with it after an hour?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-fastapi-study-group-sign-in), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-fastapi-study-group-sign-in.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-fastapi-study-group-sign-in, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
Hashed passwords, a unique email, one vague 401 and a short-lived signed token are what every real sign-in is built from, and you've now built all four with tests that prove each one.