doe/be/app/crud/user.py
2025-03-30 19:42:32 +02:00

28 lines
1.1 KiB
Python

# app/crud/user.py
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from typing import Optional
from app.models import User as UserModel # Alias to avoid name clash
from app.schemas.user import UserCreate
from app.core.security import hash_password
async def get_user_by_email(db: AsyncSession, email: str) -> Optional[UserModel]:
"""Fetches a user from the database by email."""
result = await db.execute(select(UserModel).filter(UserModel.email == email))
return result.scalars().first()
async def create_user(db: AsyncSession, user_in: UserCreate) -> UserModel:
"""Creates a new user record in the database."""
_hashed_password = hash_password(user_in.password) # Keep local var name if you like
# Create SQLAlchemy model instance - explicitly map fields
db_user = UserModel(
email=user_in.email,
# Use the correct keyword argument matching the model column name
password_hash=_hashed_password,
name=user_in.name
)
db.add(db_user)
await db.commit()
await db.refresh(db_user) # Refresh to get DB-generated values like ID, created_at
return db_user