"""User entity and value objects.""" from datetime import datetime, timezone from enum import Enum from typing import Optional import hashlib import bcrypt from sqlmodel import Field, SQLModel, Column, String, DateTime class UserStatus(str, Enum): """User account status.""" ACTIVE = "active" INACTIVE = "inactive" LOCKED = "locked" SUSPENDED = "suspended" class AuthUser(SQLModel, table=True): """User entity - represents system users (practitioners, staff, patients).""" __tablename__ = "users" __table_args__ = {'extend_existing': True} # Identity id: Optional[int] = Field(default=None, primary_key=True) username: str = Field(unique=True, index=True, max_length=100) email: str = Field(unique=True, index=True, max_length=255) # Authentication hashed_password: str = Field(max_length=255) status: UserStatus = Field(default=UserStatus.ACTIVE, sa_column=Column(String(20))) # Profile full_name: str = Field(max_length=255) phone: Optional[str] = Field(default=None, max_length=50) # User type user_type: str = Field(max_length=50, index=True) # practitioner, patient, admin, staff # Security failed_login_attempts: int = Field(default=0) last_login: Optional[datetime] = Field( default=None, sa_column=Column(DateTime(timezone=True)) ) password_changed_at: Optional[datetime] = Field( default=None, sa_column=Column(DateTime(timezone=True)) ) # MFA (optional) mfa_enabled: bool = Field(default=False) mfa_secret: Optional[str] = Field(default=None, max_length=255) # Audit created_at: datetime = Field( default_factory=lambda: datetime.now(timezone.utc), sa_column=Column(DateTime(timezone=True), nullable=False) ) updated_at: datetime = Field( default_factory=lambda: datetime.now(timezone.utc), sa_column=Column(DateTime(timezone=True), nullable=False) ) created_by: Optional[str] = Field(default=None, max_length=100) @staticmethod def hash_password(password: str) -> str: """Hash password using bcrypt with SHA256 pre-hashing for safety.""" # Pre-hash with SHA256 to handle long passwords and provide consistent length password_bytes = hashlib.sha256(password.encode('utf-8')).digest() # 32 bytes # Hash with bcrypt hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt()) return hashed.decode('utf-8') def verify_password(self, password: str) -> bool: """Verify password using bcrypt with SHA256 pre-hashing.""" password_bytes = hashlib.sha256(password.encode('utf-8')).digest() return bcrypt.checkpw(password_bytes, self.hashed_password.encode('utf-8')) def is_active(self) -> bool: """Check if user is active.""" return self.status == UserStatus.ACTIVE def is_locked(self) -> bool: """Check if user is locked.""" return self.status == UserStatus.LOCKED def increment_failed_login(self) -> None: """Increment failed login counter.""" self.failed_login_attempts += 1 if self.failed_login_attempts >= 5: self.status = UserStatus.LOCKED def reset_failed_login(self) -> None: """Reset failed login counter.""" self.failed_login_attempts = 0 self.last_login = datetime.now(timezone.utc)