
- Created User model and schemas - Implemented secure password hashing with bcrypt - Added JWT token-based authentication - Created user registration and login endpoints - Added authentication to todo routes - Updated todos to be associated with users - Created migration script for the user table - Updated documentation with auth information
71 lines
1.8 KiB
Python
71 lines
1.8 KiB
Python
from typing import List, Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoUpdate
|
|
|
|
|
|
def get_todos(db: Session, user_id: int, skip: int = 0, limit: int = 100) -> List[Todo]:
|
|
"""
|
|
Get all todo items for a specific user with pagination
|
|
"""
|
|
return db.query(Todo).filter(Todo.owner_id == user_id).offset(skip).limit(limit).all()
|
|
|
|
|
|
def get_todo(db: Session, todo_id: int, user_id: int = None) -> Optional[Todo]:
|
|
"""
|
|
Get a specific todo item by ID, optionally filtering by user_id
|
|
"""
|
|
query = db.query(Todo).filter(Todo.id == todo_id)
|
|
if user_id is not None:
|
|
query = query.filter(Todo.owner_id == user_id)
|
|
return query.first()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate, user_id: int) -> Todo:
|
|
"""
|
|
Create a new todo item
|
|
"""
|
|
db_todo = Todo(
|
|
title=todo.title,
|
|
description=todo.description,
|
|
completed=todo.completed,
|
|
owner_id=user_id,
|
|
)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def update_todo(db: Session, todo_id: int, todo: TodoUpdate, user_id: int = None) -> Optional[Todo]:
|
|
"""
|
|
Update a todo item, optionally checking owner
|
|
"""
|
|
db_todo = get_todo(db, todo_id, user_id)
|
|
if not db_todo:
|
|
return None
|
|
|
|
update_data = todo.model_dump(exclude_unset=True)
|
|
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int, user_id: int = None) -> bool:
|
|
"""
|
|
Delete a todo item, optionally checking owner
|
|
"""
|
|
db_todo = get_todo(db, todo_id, user_id)
|
|
if not db_todo:
|
|
return False
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True
|