Files
webref/backend/app/auth/repository.py
Danilo Reyes a95a4c091a phase 3.1
2025-11-01 23:33:52 -06:00

88 lines
2.1 KiB
Python

"""User repository for database operations."""
from typing import Optional
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from app.auth.security import hash_password
from app.database.models.user import User
class UserRepository:
"""Repository for user database operations."""
def __init__(self, db: Session):
"""
Initialize repository.
Args:
db: Database session
"""
self.db = db
def create_user(self, email: str, password: str) -> User:
"""
Create a new user.
Args:
email: User email (will be lowercased)
password: Plain text password (will be hashed)
Returns:
Created user instance
"""
email = email.lower()
password_hash = hash_password(password)
user = User(
email=email,
password_hash=password_hash
)
self.db.add(user)
self.db.commit()
self.db.refresh(user)
return user
def get_user_by_email(self, email: str) -> Optional[User]:
"""
Get user by email address.
Args:
email: User email to search for
Returns:
User if found, None otherwise
"""
email = email.lower()
return self.db.query(User).filter(User.email == email).first()
def get_user_by_id(self, user_id: UUID) -> Optional[User]:
"""
Get user by ID.
Args:
user_id: User UUID
Returns:
User if found, None otherwise
"""
return self.db.query(User).filter(User.id == user_id).first()
def email_exists(self, email: str) -> bool:
"""
Check if email already exists.
Args:
email: Email to check
Returns:
True if email exists, False otherwise
"""
email = email.lower()
return self.db.query(User).filter(User.email == email).first() is not None