admins.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """
  2. 管理员管理接口
  3. """
  4. from fastapi import APIRouter, Depends, Query
  5. from sqlalchemy.orm import Session
  6. from pydantic import BaseModel
  7. from app.database import get_db
  8. from app.api.deps import get_current_admin
  9. from app.models.admin import Admin
  10. from app.core.security import get_password_hash, verify_password
  11. from datetime import datetime
  12. router = APIRouter()
  13. class AdminCreate(BaseModel):
  14. """创建管理员请求"""
  15. username: str
  16. password: str
  17. real_name: str = None
  18. email: str = None
  19. role: str = "admin"
  20. class AdminUpdate(BaseModel):
  21. """更新管理员请求"""
  22. real_name: str = None
  23. email: str = None
  24. role: str = None
  25. class AdminPasswordReset(BaseModel):
  26. """重置密码请求"""
  27. new_password: str
  28. @router.get("")
  29. async def get_admins(
  30. page: int = Query(1, ge=1),
  31. page_size: int = Query(10, ge=1, le=100),
  32. keyword: str = Query(None, description="搜索关键词(用户名、邮箱)"),
  33. role: str = Query(None, description="角色筛选"),
  34. status: int = Query(None, description="状态筛选:1-正常,0-禁用"),
  35. db: Session = Depends(get_db),
  36. current_admin = Depends(get_current_admin)
  37. ):
  38. """获取管理员列表"""
  39. offset = (page - 1) * page_size
  40. query = db.query(Admin)
  41. # 搜索
  42. if keyword:
  43. query = query.filter(
  44. (Admin.username.like(f"%{keyword}%")) |
  45. (Admin.email.like(f"%{keyword}%"))
  46. )
  47. # 筛选
  48. if role:
  49. query = query.filter(Admin.role == role)
  50. if status is not None:
  51. query = query.filter(Admin.status == status)
  52. # 排序
  53. query = query.order_by(Admin.created_at.desc())
  54. admins = query.offset(offset).limit(page_size).all()
  55. total = query.count()
  56. return {
  57. "code": 200,
  58. "msg": "成功",
  59. "data": [
  60. {
  61. "id": a.id,
  62. "username": a.username,
  63. "real_name": a.real_name,
  64. "email": a.email,
  65. "role": a.role,
  66. "status": a.status,
  67. "last_login_time": a.last_login_time.isoformat() if a.last_login_time else None,
  68. "last_login_ip": a.last_login_ip,
  69. "created_at": a.created_at.isoformat() if a.created_at else None,
  70. "updated_at": a.updated_at.isoformat() if a.updated_at else None
  71. }
  72. for a in admins
  73. ],
  74. "total": total,
  75. "page": page,
  76. "page_size": page_size
  77. }
  78. @router.post("")
  79. async def create_admin(
  80. req: AdminCreate,
  81. db: Session = Depends(get_db),
  82. current_admin = Depends(get_current_admin)
  83. ):
  84. """创建管理员"""
  85. # 检查用户名是否存在
  86. existing = db.query(Admin).filter(Admin.username == req.username).first()
  87. if existing:
  88. return {"code": 400, "msg": "用户名已存在"}
  89. # 创建管理员
  90. admin = Admin(
  91. username=req.username,
  92. password=get_password_hash(req.password),
  93. real_name=req.real_name,
  94. email=req.email,
  95. role=req.role,
  96. status=1,
  97. created_at=datetime.now(),
  98. updated_at=datetime.now()
  99. )
  100. db.add(admin)
  101. db.commit()
  102. return {"code": 200, "msg": "创建成功", "data": {"id": admin.id}}
  103. @router.get("/{admin_id}")
  104. async def get_admin(
  105. admin_id: int,
  106. db: Session = Depends(get_db),
  107. current_admin = Depends(get_current_admin)
  108. ):
  109. """获取管理员详情"""
  110. admin = db.query(Admin).filter(Admin.id == admin_id).first()
  111. if not admin:
  112. return {"code": 404, "msg": "管理员不存在"}
  113. return {
  114. "code": 200,
  115. "msg": "成功",
  116. "data": {
  117. "id": admin.id,
  118. "username": admin.username,
  119. "real_name": admin.real_name,
  120. "email": admin.email,
  121. "role": admin.role,
  122. "status": admin.status,
  123. "last_login_time": admin.last_login_time.isoformat() if admin.last_login_time else None,
  124. "last_login_ip": admin.last_login_ip,
  125. "created_at": admin.created_at.isoformat() if admin.created_at else None,
  126. "updated_at": admin.updated_at.isoformat() if admin.updated_at else None
  127. }
  128. }
  129. @router.put("/{admin_id}")
  130. async def update_admin(
  131. admin_id: int,
  132. req: AdminUpdate,
  133. db: Session = Depends(get_db),
  134. current_admin = Depends(get_current_admin)
  135. ):
  136. """更新管理员"""
  137. admin = db.query(Admin).filter(Admin.id == admin_id).first()
  138. if not admin:
  139. return {"code": 404, "msg": "管理员不存在"}
  140. # 不能修改自己的角色
  141. if current_admin.id == admin_id and req.role and req.role != admin.role:
  142. return {"code": 400, "msg": "不能修改自己的角色"}
  143. # 更新字段
  144. if req.real_name is not None:
  145. admin.real_name = req.real_name
  146. if req.email is not None:
  147. admin.email = req.email
  148. if req.role is not None:
  149. admin.role = req.role
  150. admin.updated_at = datetime.now()
  151. db.commit()
  152. return {"code": 200, "msg": "更新成功"}
  153. @router.put("/{admin_id}/reset-password")
  154. async def reset_admin_password(
  155. admin_id: int,
  156. req: AdminPasswordReset,
  157. db: Session = Depends(get_db),
  158. current_admin = Depends(get_current_admin)
  159. ):
  160. """重置管理员密码"""
  161. admin = db.query(Admin).filter(Admin.id == admin_id).first()
  162. if not admin:
  163. return {"code": 404, "msg": "管理员不存在"}
  164. # 更新密码
  165. admin.password = get_password_hash(req.new_password)
  166. admin.updated_at = datetime.now()
  167. db.commit()
  168. return {"code": 200, "msg": "密码重置成功"}
  169. @router.put("/{admin_id}/status")
  170. async def update_admin_status(
  171. admin_id: int,
  172. status: int = Query(..., description="状态:1-正常,0-禁用"),
  173. db: Session = Depends(get_db),
  174. current_admin = Depends(get_current_admin)
  175. ):
  176. """启用/禁用管理员"""
  177. admin = db.query(Admin).filter(Admin.id == admin_id).first()
  178. if not admin:
  179. return {"code": 404, "msg": "管理员不存在"}
  180. # 不能禁用自己
  181. if current_admin.id == admin_id:
  182. return {"code": 400, "msg": "不能禁用自己"}
  183. admin.status = status
  184. admin.updated_at = datetime.now()
  185. db.commit()
  186. return {"code": 200, "msg": "状态更新成功"}
  187. @router.delete("/{admin_id}")
  188. async def delete_admin(
  189. admin_id: int,
  190. db: Session = Depends(get_db),
  191. current_admin = Depends(get_current_admin)
  192. ):
  193. """删除管理员"""
  194. admin = db.query(Admin).filter(Admin.id == admin_id).first()
  195. if not admin:
  196. return {"code": 404, "msg": "管理员不存在"}
  197. # 不能删除自己
  198. if current_admin.id == admin_id:
  199. return {"code": 400, "msg": "不能删除自己"}
  200. db.delete(admin)
  201. db.commit()
  202. return {"code": 200, "msg": "删除成功"}