notesapi-q3b8fl/app/crud/crud_user.py
Automated Action 741f301b11 Implement Notes API with FastAPI and SQLite
- Set up project structure with FastAPI
- Implement user authentication system with JWT tokens
- Create database models for users, notes, and collections
- Set up SQLAlchemy ORM and Alembic migrations
- Implement CRUD operations for notes and collections
- Add filtering and sorting capabilities for notes
- Implement health check endpoint
- Update project documentation
2025-05-31 14:54:14 +00:00

66 lines
1.8 KiB
Python

from typing import Any
from sqlalchemy.orm import Session
from app.core.security import get_password_hash, verify_password
from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
def get_by_email(db: Session, email: str) -> User | None:
return db.query(User).filter(User.email == email).first()
def get_by_username(db: Session, username: str) -> User | None:
return db.query(User).filter(User.username == username).first()
def get(db: Session, user_id: int) -> User | None:
return db.query(User).filter(User.id == user_id).first()
def create(db: Session, obj_in: UserCreate) -> User:
db_obj = User(
email=obj_in.email,
username=obj_in.username,
hashed_password=get_password_hash(obj_in.password),
is_active=True,
)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
db: Session, db_obj: User, obj_in: UserUpdate | dict[str, Any]
) -> User:
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
if update_data.get("password"):
hashed_password = get_password_hash(update_data["password"])
del update_data["password"]
update_data["hashed_password"] = hashed_password
for field in update_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def authenticate(db: Session, email: str, password: str) -> User | None:
user = get_by_email(db, email=email)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
def is_active(user: User) -> bool:
return user.is_active