173 lines
4.5 KiB
Python

from datetime import datetime
from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING
from sqlalchemy import select
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
# For type hints
if TYPE_CHECKING:
pass
async def get_by_id(db: Session, user_id: str) -> Optional[User]:
"""
Get a user by ID.
"""
# Check if db has execute method (AsyncSession)
if hasattr(db, "execute"):
result = await db.execute(select(User).filter(User.id == user_id))
return result.scalars().first()
# Synchronous operation
return db.query(User).filter(User.id == user_id).first()
async def get_by_email(db: Session, email: str) -> Optional[User]:
"""
Get a user by email.
"""
# Check if db has execute method (AsyncSession)
if hasattr(db, "execute"):
result = await db.execute(select(User).filter(User.email == email))
return result.scalars().first()
# Synchronous operation
return db.query(User).filter(User.email == email).first()
async def get_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]:
"""
Get a list of users with pagination.
"""
# Check if db has execute method (AsyncSession)
if hasattr(db, "execute"):
result = await db.execute(select(User).offset(skip).limit(limit))
return result.scalars().all()
# Synchronous operation
return db.query(User).offset(skip).limit(limit).all()
async def create(db: Session, *, obj_in: UserCreate) -> User:
"""
Create a new user.
"""
db_obj = User(
email=obj_in.email,
hashed_password=get_password_hash(obj_in.password),
full_name=obj_in.full_name,
is_active=True,
is_superuser=False,
email_verified=False,
)
db.add(db_obj)
# Check if db has commit method that's a coroutine
if (
hasattr(db, "commit")
and callable(db.commit)
and hasattr(db.commit, "__await__")
):
await db.commit()
await db.refresh(db_obj)
else:
# Synchronous operation
db.commit()
db.refresh(db_obj)
return db_obj
async def update(
db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
) -> User:
"""
Update a user.
"""
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
if "password" in update_data and update_data["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 hasattr(db_obj, field):
setattr(db_obj, field, update_data[field])
db.add(db_obj)
# Check if db has commit method that's a coroutine
if (
hasattr(db, "commit")
and callable(db.commit)
and hasattr(db.commit, "__await__")
):
await db.commit()
await db.refresh(db_obj)
else:
# Synchronous operation
db.commit()
db.refresh(db_obj)
return db_obj
async def remove(db: Session, *, id: str) -> Optional[User]:
"""
Delete a user.
"""
user = await get_by_id(db, id)
if user:
if (
hasattr(db, "delete")
and callable(db.delete)
and hasattr(db.delete, "__await__")
):
await db.delete(user)
await db.commit()
else:
# Synchronous operation
db.delete(user)
db.commit()
return user
async def authenticate(db: Session, *, email: str, password: str) -> Optional[User]:
"""
Authenticate a user by email and password.
"""
user = await get_by_email(db, email=email)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
async def update_last_login(db: Session, *, user: User) -> User:
"""
Update the last login timestamp for a user.
"""
user.last_login = datetime.utcnow()
db.add(user)
# Check if db has commit method that's a coroutine
if (
hasattr(db, "commit")
and callable(db.commit)
and hasattr(db.commit, "__await__")
):
await db.commit()
await db.refresh(user)
else:
# Synchronous operation
db.commit()
db.refresh(user)
return user