# 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 November 19, 2026

By Gregor Dzierzon

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](https://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:

```bash
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):

```powershell
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
```

On a Mac (zsh):

```bash
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_token` and `student_id_from_token`, and the `SECRET_KEY` line, all yours to write.
- `routers/auth.py`: the routes, for you to write. The models, `SignUp` and `StudentOut`, and the token reader, `oauth2_scheme`, are ready.
- `students_data.py`: every SQL statement: `add_student` (which raises `DuplicateEmail` for a used email), `find_student_by_email` (which includes the hash, for checking a sign-in) and `get_student` (which doesn't).
- `database.py`, `migrations/0001_create_students.sql` and `main.py`: the database file, the students table with its `UNIQUE` email, the `get_db` dependency, 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's `tmp_path` with two students, Maya and Theo, as *Testing with a Real, Throwaway Database* does. You don't need to change it.
- `requirements.txt` and `pytest.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:

```text
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
```

1. **Write `security.py`.** Read `SECRET_KEY` from the environment variable `JWT_SECRET`. Then `hash_password` and `check_password` with pwdlib, and `make_token` and `student_id_from_token` with PyJWT, as the comment at the top describes.
2. **Sign up** with `POST /auth/sign-up`: hash the password, save the student, answer 201 with `StudentOut`, and turn `DuplicateEmail` into a 409.
3. **Sign in** with `POST /auth/token`: take `OAuth2PasswordRequestForm`, check the password, and answer the token, or the 401 with its header.
4. **Answer `GET /me`** with 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:

```bash
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_password` and `check_password` are one line each: `password_hash.hash(password)` and `password_hash.verify(password, hashed)`.
- **`make_token`** is the one from *Tokens: Signing In with a JWT*, with `timedelta(minutes=TOKEN_MINUTES)`. PyJWT wants `sub` as text, so it's `str(student_id)` going in and `int(payload["sub"])` coming out.
- **`student_id_from_token`** puts `jwt.decode` in a `try`. `except jwt.InvalidTokenError:` catches an expired token, another key's signature and text that isn't a token, all at once: return `None`.
- **Sign-up answers without the password.** `response_model=StudentOut` sends only `id`, `name` and `email`, and `students_data.get_student(conn, student_id)` gives exactly those for the new student.
- **Every 401 is the same `HTTPException`**, with `headers={"WWW-Authenticate": "Bearer"}`. A small function that makes it, given the detail, saves writing it three times. The handler in `main.py` passes the header on in the one error shape.
- **In `GET /me`**, a bad token gives `None` from `student_id_from_token`, and a deleted student gives `None` from `get_student`. One `if 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.

1. 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.
2. 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:

   ```bash
   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 main
   ```

3. Paste 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.

## Key terms

- [Hashing](https://www.ask-codey.com/glossary/hashing)
- [Argon2](https://www.ask-codey.com/glossary/argon2)
- [JWT](https://www.ask-codey.com/glossary/jwt)
- [Bearer Token](https://www.ask-codey.com/glossary/bearer-token)
- [409 Conflict](https://www.ask-codey.com/glossary/409-conflict)
- [401 Unauthorized](https://www.ask-codey.com/glossary/401-unauthorized)

## Related

- [Storing Passwords Safely: Hashing with pwdlib](https://www.ask-codey.com/lessons/fastapi-auth-passwords-and-hashing)
- [Sign-Up and Sign-In Routes](https://www.ask-codey.com/lessons/fastapi-auth-sign-up-and-sign-in)
- [Tokens: Signing In with a JWT](https://www.ask-codey.com/lessons/fastapi-auth-tokens-jwt)

Source: https://www.ask-codey.com/lessons/exercise-fastapi-study-group-sign-in
