user.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Depends, Path, Query
  4. from sqlalchemy import text
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from sqlalchemy.sql import or_, and_
  7. from core.security import hashed_password
  8. from crud.sysdata.role import crud_role
  9. from crud.user.user import crud_admin
  10. from models.user import Admin
  11. from schemas.base import ReturnField, OrderByField
  12. from schemas.user import CreateAdminUser, AdminUserDetail, UpdateAdminUser, AdminUserList
  13. from utils.depends import get_async_db, get_current_user
  14. router = APIRouter()
  15. @router.post("/sysuser", summary="新增管理员", response_model=AdminUserDetail)
  16. async def create_admin(user: CreateAdminUser,
  17. db: AsyncSession = Depends(get_async_db),
  18. current_user: Admin = Depends(get_current_user)):
  19. user_in = user.dict(exclude_none=True)
  20. if not user:
  21. return {"errcode": 400, "mess": "请求参数为空!"}
  22. # 判断是否存在同名
  23. _q = [or_(Admin.username == user_in["username"], Admin.phone == user_in["phone"])]
  24. db_user = await crud_admin.find_one(db, filters=_q)
  25. if db_user:
  26. return {"errcode": 400, "mess": "账号或手机号已存在!"}
  27. user_in["creator_id"] = current_user.id
  28. user_in["creator_name"] = current_user.username
  29. user_in["editor_id"] = current_user.id
  30. user_in["editor_name"] = current_user.username
  31. user_in["password"] = hashed_password(user.password)
  32. db_user = await crud_admin.insert_one(db, user_in)
  33. return {"data": db_user}
  34. @router.put("/sysuser/{uid}", summary="修改管理员", response_model=AdminUserDetail)
  35. async def update_admin(user: UpdateAdminUser,
  36. uid: int = Path(..., description="管理员ID"),
  37. db: AsyncSession = Depends(get_async_db),
  38. current_user: Admin = Depends(get_current_user)):
  39. user_in = user.dict(exclude_none=True)
  40. if not user:
  41. return {"errcode": 400, "mess": "请求参数为空!"}
  42. # 判断是否存在同名
  43. _q = [and_(Admin.id != uid, Admin.phone == user_in["phone"])]
  44. db_user = await crud_admin.find_one(db, filters=_q)
  45. if db_user:
  46. return {"errcode": 400, "mess": "账号或手机号已存在!"}
  47. user_in["editor_id"] = current_user.id
  48. user_in["editor_name"] = current_user.username
  49. db_user = await crud_admin.update(db, db_user, user_in)
  50. return {"data": db_user}
  51. @router.delete("/sysuser/{uid}", summary="删除管理员", response_model=AdminUserDetail)
  52. async def delete_admin(uid: int = Path(..., description="管理员ID"),
  53. db: AsyncSession = Depends(get_async_db),
  54. current_user: Admin = Depends(get_current_user)):
  55. # 不允许删除初始管理员账号
  56. if uid == 1:
  57. return {"errcode": 400, "mess": "该用户不允许删除!"}
  58. existed = await crud_admin.count(db, filters={"id": uid})
  59. if not existed:
  60. return {"errcode": 404, "mess": "管理员不存在!"}
  61. else:
  62. await crud_admin.delete(db, obj_id=uid)
  63. return {"data": None}
  64. @router.get("/sysuser/{uid}", summary="获取管理员详情", response_model=AdminUserDetail)
  65. async def get_admin(uid: int = Path(..., description="管理员ID"),
  66. db: AsyncSession = Depends(get_async_db),
  67. current_user: Admin = Depends(get_current_user)):
  68. db_obj = await crud_admin.find_one(db, filters={"id": uid})
  69. if not db_obj:
  70. return {"errcode": 404, "mess": "管理员不存在!"}
  71. else:
  72. return {"data": db_obj}
  73. @router.get("/sysusers",
  74. summary="获取管理员列表",
  75. response_model=AdminUserList,
  76. response_model_exclude_none=True)
  77. async def get_admin_list(page: int = 1,
  78. size: int = 10,
  79. username: str = "",
  80. name: str = "",
  81. phone: str = "",
  82. order: OrderByField = Query(
  83. "-created_at", description="排序字段,用逗号分隔,升降序以-判断,默认-created_at"),
  84. res: ReturnField = Query("",
  85. description="返回字段,取值范围:id,username,name,phone"),
  86. db: AsyncSession = Depends(get_async_db),
  87. current_user: Admin = Depends(get_current_user)):
  88. _q = []
  89. if username:
  90. _q.append(Admin.username.like(f"%{username}%"))
  91. if name:
  92. _q.append(Admin.name.like(f"%{name}%"))
  93. if phone:
  94. _q.append(Admin.phone.like(f"%{phone}%"))
  95. offset = (page - 1) * size
  96. if isinstance(order, str):
  97. order = [text(order)]
  98. total, items = await crud_admin.find_all(db,
  99. filters=_q,
  100. offset=offset,
  101. limit=size,
  102. order_by=order,
  103. return_fields=res)
  104. for item in items:
  105. print(item.role_id)
  106. role = await crud_role.find_one(db, filters={"id": item.role_id})
  107. item.role_name = role.name
  108. return {"total": total, "data": items}