Now that we have our users
table and endpoints for creating and retrieving users, we can implement user registration and write tests to ensure our implementation is correct.
Implementing User Registration
Python
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.models import User, UserCreate
from app.schemas import UserSchema
from app.utils import hash_password
router = APIRouter()
@router.post("/register", response_model=UserSchema)
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
# Check if user already exists
existing_user = await db.query(User).filter(User.email == user.email).first()
if existing_user:
raise HTTPException(status_code=400, detail="User already exists")
# Hash the password
hashed_password = hash_password(user.password)
# Create the user
db_user = User(email=user.email, password=hashed_password)
db.add(db_user)
await db.commit()
await db.refresh(db_user)
return db_user
Writing Tests
Python
import pytest
from app.schemas import UserSchema
def test_register_user(client, db_session):
data = {"email": "[email protected]", "password": "password123"}
response = client.post("/register", json=data)
assert response.status_code == 200
user = response.json()
assert user["email"] == data["email"]
assert user["password"] is None # Password should not be returned in the response
# Check if user is created in the database
db_user = db_session.query(User).filter(User.email == data["email"]).first()
assert db_user is not None
assert db_user.email == data["email"]
Terms:
- Password Validation: Implement password validation rules (e.g., minimum length, complexity) to ensure strong passwords.
- Email Verification: Consider sending a verification email to the user’s registered email address to confirm their account.
- Error Handling: Handle potential errors like database errors or invalid input.
- Security: Protect against common security vulnerabilities like SQL injection and cross-site scripting.