"""SQLAlchemy models for authentication 資料表結構: - user_sessions: 儲存使用者 session 資料,包含加密密碼用於自動刷新 - users: 永久儲存使用者資訊 (用於報告生成時的姓名解析) """ from sqlalchemy import Column, Integer, String, DateTime, Index from datetime import datetime from app.core.database import Base class UserSession(Base): """User session model with encrypted password for auto-refresh""" __tablename__ = "user_sessions" id = Column(Integer, primary_key=True, index=True) username = Column(String(255), nullable=False, comment="User email from AD") display_name = Column(String(255), nullable=False, comment="Display name for chat") internal_token = Column( String(255), unique=True, nullable=False, index=True, comment="Internal session token (UUID)" ) ad_token = Column(String(500), nullable=False, comment="AD API token") encrypted_password = Column(String(500), nullable=False, comment="AES-256 encrypted password") ad_token_expires_at = Column(DateTime, nullable=False, comment="AD token expiry time") refresh_attempt_count = Column( Integer, default=0, nullable=False, comment="Failed refresh attempts counter" ) last_activity = Column( DateTime, default=datetime.utcnow, nullable=False, comment="Last API request time" ) created_at = Column(DateTime, default=datetime.utcnow, nullable=False) class User(Base): """Permanent user information for display name resolution in reports This table stores user information from AD API and persists even after session expiration. Used for: - Displaying user names (instead of emails) in generated reports - Tracking user metadata (office location, job title) """ __tablename__ = "users" user_id = Column( String(255), primary_key=True, comment="User email address (e.g., ymirliu@panjit.com.tw)" ) display_name = Column( String(255), nullable=False, comment="Display name from AD (e.g., 'ymirliu 劉念蓉')" ) office_location = Column( String(100), nullable=True, comment="Office location from AD (e.g., '高雄')" ) job_title = Column( String(100), nullable=True, comment="Job title from AD" ) last_login_at = Column( DateTime, nullable=True, comment="Last login timestamp" ) created_at = Column( DateTime, default=datetime.utcnow, nullable=False, comment="First login timestamp" ) # Indexes __table_args__ = ( Index("ix_users_display_name", "display_name"), )