keys.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """
  2. 密钥管理接口
  3. """
  4. from fastapi import APIRouter, Depends, Request
  5. from sqlalchemy.orm import Session
  6. from fastapi import Body
  7. from app.database import get_db
  8. from app.api.deps import get_current_admin
  9. from app.models.api_key import APIKey
  10. from app.models.key_rotation_config import KeyRotationConfig
  11. from app.core.encrypt import encryptor
  12. from datetime import datetime, timedelta
  13. from app.utils.timezone import beijing_now
  14. from app.config import settings
  15. router = APIRouter()
  16. @router.get("/current")
  17. async def get_current_key(
  18. db: Session = Depends(get_db),
  19. current_admin = Depends(get_current_admin)
  20. ):
  21. """获取当前密钥"""
  22. key = db.query(APIKey).filter(APIKey.is_active == 1).order_by(APIKey.key_version.desc()).first()
  23. if not key:
  24. return {"code": 404, "msg": "未找到激活的密钥"}
  25. return {
  26. "code": 200,
  27. "msg": "成功",
  28. "data": {
  29. "public_key": key.public_key,
  30. "private_key": key.private_key,
  31. "key_version": key.key_version,
  32. "expire_at": key.expire_at.isoformat() if key.expire_at else None
  33. }
  34. }
  35. @router.get("/history")
  36. async def get_key_history(
  37. db: Session = Depends(get_db),
  38. current_admin = Depends(get_current_admin)
  39. ):
  40. """获取历史密钥"""
  41. keys = db.query(APIKey).order_by(APIKey.key_version.desc()).all()
  42. return {
  43. "code": 200,
  44. "msg": "成功",
  45. "data": [
  46. {
  47. "id": k.id,
  48. "key_version": k.key_version,
  49. "is_active": bool(k.is_active),
  50. "created_at": k.created_at.isoformat() if k.created_at else None,
  51. "expire_at": k.expire_at.isoformat() if k.expire_at else None
  52. }
  53. for k in keys
  54. ]
  55. }
  56. @router.post("/rotate")
  57. async def rotate_key(
  58. request: Request,
  59. db: Session = Depends(get_db),
  60. current_admin = Depends(get_current_admin)
  61. ):
  62. """立即更新密钥"""
  63. # 获取当前激活的密钥
  64. current_key = db.query(APIKey).filter(APIKey.is_active == 1).order_by(APIKey.key_version.desc()).first()
  65. # 生成新密钥
  66. new_key_pair = encryptor.generate_key_pair()
  67. new_version = (current_key.key_version + 1) if current_key else 1
  68. # 获取配置,确定过期时间
  69. config = db.query(KeyRotationConfig).first()
  70. rotation_days = config.rotation_days if config else settings.KEY_ROTATION_DAYS
  71. expire_at = beijing_now() + timedelta(days=rotation_days)
  72. # 禁用旧密钥
  73. if current_key:
  74. current_key.is_active = 0
  75. current_key.updated_at = beijing_now()
  76. # 创建新密钥
  77. new_key = APIKey(
  78. public_key=new_key_pair['public_key'],
  79. private_key=new_key_pair['private_key'],
  80. key_version=new_version,
  81. is_active=1,
  82. expire_at=expire_at,
  83. created_at=beijing_now(),
  84. updated_at=beijing_now()
  85. )
  86. db.add(new_key)
  87. # 刷新以获取ID
  88. db.flush()
  89. # 创建历史记录
  90. from app.utils.history import create_api_key_history, create_operation_log
  91. if current_key:
  92. create_api_key_history(db, current_key, "UPDATE")
  93. create_api_key_history(db, new_key, "INSERT")
  94. # 记录操作日志
  95. client_ip = request.client.host if request.client else None
  96. old_version = current_key.key_version if current_key else None
  97. create_operation_log(
  98. db=db,
  99. admin_id=current_admin.id,
  100. module="密钥管理",
  101. action="密钥轮换",
  102. description=f"执行密钥轮换:版本 {old_version} -> {new_version}",
  103. old_data={"old_version": old_version},
  104. new_data={"new_version": new_version, "rotation_days": rotation_days},
  105. ip_address=client_ip
  106. )
  107. # 一次性提交所有更改
  108. db.commit()
  109. return {
  110. "code": 200,
  111. "msg": "密钥更新成功",
  112. "data": {
  113. "public_key": new_key.public_key,
  114. "private_key": new_key.private_key,
  115. "key_version": new_key.key_version,
  116. "expire_at": new_key.expire_at.isoformat() if new_key.expire_at else None
  117. }
  118. }
  119. @router.put("/cycle")
  120. async def update_key_cycle(
  121. req: dict = Body(...),
  122. request: Request = None,
  123. db: Session = Depends(get_db),
  124. current_admin = Depends(get_current_admin)
  125. ):
  126. """更新密钥轮换周期"""
  127. rotation_days = req.get("rotation_days")
  128. if not rotation_days or rotation_days < 1:
  129. return {"code": 400, "msg": "轮换周期必须大于0"}
  130. # 获取或创建配置
  131. config = db.query(KeyRotationConfig).first()
  132. old_rotation_days = config.rotation_days if config else None
  133. if not config:
  134. config = KeyRotationConfig(
  135. rotation_days=rotation_days,
  136. is_auto_rotate=1,
  137. updated_at=beijing_now()
  138. )
  139. db.add(config)
  140. else:
  141. config.rotation_days = rotation_days
  142. config.updated_at = beijing_now()
  143. # 创建历史记录
  144. from app.utils.history import create_key_rotation_config_history, create_operation_log
  145. create_key_rotation_config_history(db, config, "INSERT" if not old_rotation_days else "UPDATE")
  146. # 记录操作日志
  147. client_ip = request.client.host if request and request.client else None
  148. create_operation_log(
  149. db=db,
  150. admin_id=current_admin.id,
  151. module="密钥管理",
  152. action="更新轮换周期",
  153. description=f"更新密钥轮换周期:{old_rotation_days}天 -> {rotation_days}天",
  154. old_data={"rotation_days": old_rotation_days},
  155. new_data={"rotation_days": rotation_days},
  156. ip_address=client_ip
  157. )
  158. # 一次性提交所有更改
  159. db.commit()
  160. return {"code": 200, "msg": "更新成功"}