platform_api_key.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """
  2. 平台API Key数据ORM定义
  3. 定义平台API Key的数据库表结构,用于存储用户创建的API密钥信息
  4. 用于调用本平台开放API的密钥管理
  5. """
  6. from datetime import datetime
  7. from sqlalchemy import Column, Integer, String, DateTime, Index, ForeignKey
  8. from sqlalchemy.sql import func
  9. from sqlalchemy.orm import relationship
  10. from app.database import Base
  11. class PlatformApiKey(Base):
  12. """
  13. 平台API Key ORM类
  14. 存储用户创建的平台API密钥信息
  15. - API Key使用SHA256哈希存储,仅在创建时返回完整密钥
  16. - 每个用户最多可创建5个有效API Key
  17. - 支持启用/禁用状态管理
  18. """
  19. __tablename__ = "platform_api_key"
  20. # 主键ID
  21. id = Column(
  22. Integer,
  23. primary_key=True,
  24. autoincrement=True,
  25. comment="主键ID"
  26. )
  27. # 用户ID(外键关联users表)
  28. user_id = Column(
  29. String(50),
  30. ForeignKey("aigcspace.users.id", ondelete="CASCADE"),
  31. nullable=False,
  32. comment="用户ID"
  33. )
  34. # API Key(SHA256哈希存储)
  35. api_key = Column(
  36. String(100),
  37. nullable=False,
  38. comment="API Key(SHA256哈希)"
  39. )
  40. # API Key前缀(用于显示,如sk-aigc-xxxx...xxxx)
  41. api_key_prefix = Column(
  42. String(20),
  43. nullable=False,
  44. comment="API Key前缀用于显示"
  45. )
  46. # 备注名称
  47. name = Column(
  48. String(100),
  49. nullable=True,
  50. comment="备注名称"
  51. )
  52. # 状态:active/disabled
  53. status = Column(
  54. String(20),
  55. nullable=False,
  56. default="active",
  57. comment="状态:active/disabled"
  58. )
  59. # 密钥类型:public(公钥,访问云端模型)/ local(本地私钥,访问本地模型)
  60. key_type = Column(
  61. String(20),
  62. nullable=False,
  63. default="public",
  64. comment="密钥类型:public/local"
  65. )
  66. # 最后使用时间
  67. last_used_at = Column(
  68. DateTime,
  69. nullable=True,
  70. comment="最后使用时间"
  71. )
  72. # 创建时间(自动设置)
  73. created_at = Column(
  74. DateTime,
  75. nullable=False,
  76. server_default=func.now(),
  77. comment="创建时间"
  78. )
  79. # 更新时间(自动更新)
  80. updated_at = Column(
  81. DateTime,
  82. nullable=False,
  83. server_default=func.now(),
  84. onupdate=func.now(),
  85. comment="更新时间"
  86. )
  87. # 表级配置
  88. __table_args__ = (
  89. Index('idx_platform_api_key_user_id', 'user_id'),
  90. Index('idx_platform_api_key_api_key', 'api_key'),
  91. Index('idx_platform_api_key_status', 'status'),
  92. {'schema': 'aigcspace', 'comment': '平台API Key表'}
  93. )
  94. def __repr__(self):
  95. return f"<PlatformApiKey(id={self.id}, user_id='{self.user_id}', prefix='{self.api_key_prefix}', status='{self.status}')>"