Creating Users
NotesOnce again, we’ll begin by creating a new database schema for user accounts. Then, we’ll work purely on implementing APIs for creating and validating users. Once we can authenticate users and generate JWT tokens, we’ll switch back to the web pages, and leveraging the user APIs, implement a user login page and do some refactoring to restrict certain areas and functionality depending on user authorisation.
Install the Python package pwdlib with Argon2 support. Storing plain text passwords in the database is a bad idea, so only a hash of each password is stored: a one-way scramble that can check a password, but can’t be turned back into it. Argon2 is the current recommendation for password hashing, and is what the FastAPI documentation now uses.
pip install "pwdlib[argon2]"Add it to the non_ver_reqs.txt file:
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillow
captcha
pwdlib[argon2]And freeze the requirements:
pip freeze > requirements.txtOlder guides (including earlier versions of this one) use passlib[bcrypt]. passlib is no longer maintained, and fails with recent versions of the bcrypt package. Email validation for EmailStr needs the email-validator package, which fastapi[standard] already includes, so pydantic[email] isn’t needed either.
Add the following user schemas. A key thing to point out is how the UserIn model has a field called password yet the database model User has hashed_password. While they are both type str, it’s important that it’s clear that only hashed values are stored. UserOut, the response model, has neither.
Another observation is that I’m using the user’s email for both the email and username fields.
import uuid
import datetime
from pydantic import ConfigDict, EmailStr
from sqlmodel import SQLModel, Field
class UserIn(SQLModel):
first_name: str
last_name: str
email: EmailStr
username: EmailStr
profile_image: str
is_superuser: bool = False
is_active: bool = True
is_author: bool = False
is_member: bool = False
password: str = Field(min_length=8)
model_config = ConfigDict(
json_schema_extra={
"example": {
"first_name": "John",
"last_name": "Smith",
"email": "jsmith@email.com",
"username": "jsmith@email.com",
"profile_image": "/static/img/profile.jpg",
"is_superuser": True,
"is_active": True,
"is_author": True,
"is_member": False,
"password": "changeme",
}
}
)
class UserOut(SQLModel):
id: uuid.UUID
first_name: str
last_name: str
email: EmailStr
username: EmailStr
profile_image: str
is_superuser: bool
is_active: bool
is_author: bool
is_member: bool
created_date: datetime.datetime
# SQLModel Database Schemas
class User(SQLModel, table=True):
id: uuid.UUID = Field(
default_factory=uuid.uuid4,
primary_key=True)
first_name: str
last_name: str
email: EmailStr = Field(unique=True, index=True)
username: EmailStr = Field(unique=True, index=True)
profile_image: str
is_superuser: bool = False
is_active: bool = True
is_author: bool = False
is_member: bool = False
hashed_password: str
created_date: datetime.datetime = Field(
default_factory=lambda: datetime.datetime.now(datetime.UTC))Field(unique=True, index=True) makes the database itself refuse two users with the same email address, and makes looking users up by email fast. Field(min_length=8) on the password means Pydantic rejects anything shorter.
With the new user schema added, once again you’ll have to let Alembic know it now exists:
from db.schemas.blog_schemas import BlogPost
from db.schemas.captcha_schemas import Captcha
from db.schemas.user_schemas import User # NEWAnd create a new revision:
alembic revision --autogenerate -m "added user table"alembic upgrade headNext, add the following API file, containing a function get_password_hash_api to hash passwords, and a route create_user_api to create a new user in the database:
from fastapi import APIRouter, Depends, HTTPException, status
from pwdlib import PasswordHash
from sqlmodel import Session, select
from db.db import get_session_db
from db.schemas.user_schemas import User, UserIn, UserOut
router = APIRouter()
password_hash = PasswordHash.recommended()
# Functions
def get_password_hash_api(password: str) -> str:
return password_hash.hash(password)
# APIs
@router.post('/auth/create/user', status_code=status.HTTP_201_CREATED)
def create_user_api(user_in: UserIn, session: Session = Depends(get_session_db)) -> UserOut:
if session.exec(select(User).where(User.email == user_in.email)).first():
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="A user with that email already exists.")
new_user = User.model_validate(user_in, update={"hashed_password": get_password_hash_api(user_in.password)})
session.add(new_user)
session.commit()
session.refresh(new_user)
return new_userPasswordHash.recommended() sets up Argon2 with sensible settings. User.model_validate(user_in, update=...) creates the table model from the input, adding the hashed_password. The plain password isn’t a field of User, so it’s never stored. If the email is already taken, the API responds with 409 Conflict.
Include the auth_apis router in main.py, alongside the blog APIs:
from api import health_api, blog_apis, captcha_apis, auth_apis # UPDATED if settings.CONF_ENABLE_APIS:
main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"])
main_app.include_router(auth_apis.router, prefix=settings.CONF_API_V1_STR, tags=["auth_apis"]) # NEWThese APIs have no authentication of their own: anyone who can reach /api/v1/auth/create/user can create a user, even a superuser, and the blog APIs can create and delete posts. That’s why CONF_ENABLE_APIS defaults to false (see Disable API Access). Turn them on in development only, with CONF_ENABLE_APIS=true in your .env.
Now run the application and head to http://localhost:8000/docs and add the example user:
Notice how the password provided was changeme but the response body contains no password at all. In the database, hashed_password holds something like $argon2id$v=19$m=65536,t=3,p=4$...: the algorithm, its settings, a random salt and the hash.
Creating users from the command line#
With the APIs switched off in production, you still need a way to create the first author or admin. A small script does the job:
"""Create a user from the command line, for example the first author or admin.
python -m db.create_user jsmith@email.com John Smith --author --superuser
"""
import argparse
import getpass
from sqlmodel import Session, select
from api.auth_apis import get_password_hash_api
from db.db import engine
from db.schemas.user_schemas import User
def main():
parser = argparse.ArgumentParser(description="Create a user.")
parser.add_argument("email")
parser.add_argument("first_name")
parser.add_argument("last_name")
parser.add_argument("--author", action="store_true", help="can create and edit blog posts")
parser.add_argument("--superuser", action="store_true", help="can use the site admin pages")
args = parser.parse_args()
password = getpass.getpass("Password: ")
if len(password) < 8 or password != getpass.getpass("Password (again): "):
raise SystemExit("Passwords must match and be at least 8 characters.")
with Session(engine) as session:
if session.exec(select(User).where(User.email == args.email)).first():
raise SystemExit(f"A user with the email {args.email} already exists.")
session.add(User(first_name=args.first_name, last_name=args.last_name,
email=args.email, username=args.email,
profile_image="/static/img/profile.jpg",
is_author=args.author, is_superuser=args.superuser,
hashed_password=get_password_hash_api(password)))
session.commit()
print(f"Created {args.email}.")
if __name__ == "__main__":
main()python -m db.create_user jsmith@email.com John Smith --author --superuserIt asks for the password twice with getpass, so it’s never shown on screen or saved in your shell history.