user.py 2.54 KB
# -*- coding: utf-8 -*-
"""
文件名: app/models/user.py
职责: 用户、登录尝试、验证码等认证相关 ORM 模型。
注意: 不要删除这个注释。
"""

from datetime import datetime
from sqlalchemy import BigInteger, Boolean, Column, DateTime, String, Integer
from sqlalchemy.orm import declarative_base

Base = declarative_base()


class User(Base):
    """系统用户表"""
    __tablename__ = "sys_user"

    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="主键ID")
    username = Column(String(50), nullable=False, unique=True, comment="账号")
    hashed_password = Column(String(255), nullable=False, comment="加密密码")
    is_active = Column(Boolean, nullable=False, default=True, comment="是否启用")
    is_superuser = Column(Boolean, nullable=False, default=False, comment="是否超级管理员")
    failed_attempts = Column(Integer, nullable=False, default=0, comment="连续失败次数")
    locked_until = Column(DateTime, nullable=True, comment="锁定截止时间")
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username})>"


class LoginAttempt(Base):
    """登录尝试记录表"""
    __tablename__ = "sys_login_attempt"

    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="主键ID")
    username = Column(String(50), nullable=False, comment="账号")
    ip_address = Column(String(64), nullable=True, comment="IP地址")
    success = Column(Boolean, nullable=False, default=False, comment="是否成功")
    fail_reason = Column(String(255), nullable=True, comment="失败原因")
    attempted_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="尝试时间")

    def __repr__(self):
        return f"<LoginAttempt(id={self.id}, username={self.username}, success={self.success})>"


class Captcha(Base):
    """图形验证码表"""
    __tablename__ = "sys_captcha"

    token = Column(String(64), primary_key=True, comment="验证码令牌")
    code = Column(String(10), nullable=False, comment="验证码内容")
    expire_at = Column(DateTime, nullable=False, comment="过期时间")
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="创建时间")

    def __repr__(self):
        return f"<Captcha(token={self.token})>"