The User Model

Create auth.py with a User model that stores email and hashed password

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Users need a database table

Your expense tracker stores expenses in a database table. User accounts need the same treatment. Each user has three fields:

  • id: an auto-assigned integer, same pattern as Expense
  • email: the user's login identifier — must be unique so two users cannot register with the same address
  • password_hash: the hashed version of the user's password — you never store plain text passwords

The email field uses unique=True to prevent duplicate registrations. It also uses index=True so the database can find a user by email quickly during login, without scanning every row.

This chapter creates a new file called auth.py. It starts small — just the model — and grows across the next three chapters.

Instructions

Create auth.py with the User model.

  1. Define a class called User that extends SQLModel with table=True — this creates a database table called user, just like Expense creates an expense table.
  2. Add an id field: id: Optional[int] = Field(default=None, primary_key=True) — the database assigns this automatically when a new user is created.
  3. Add an email field: email: str = Field(unique=True, index=True)unique=True prevents two users from registering with the same email, and index=True makes login lookups fast.
  4. Add a password_hash field as a plain str with no constraints. This stores the hashed version of the password, never the original.