AdminService.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import json
  2. import uuid
  3. from datetime import timedelta
  4. from django.core.exceptions import ObjectDoesNotExist
  5. from django.core.paginator import Paginator
  6. from django.db import transaction
  7. from django.shortcuts import get_object_or_404
  8. from DCbackend.utils.common import success, fail, pageData
  9. from DCbackend.utils.token import encrypt, decrypt
  10. from backend.Form.UserForm import UserForm
  11. from backend.Service.AdminRoleService import AdminRoleService
  12. from backend.Service.AuthMenuService import AuthMenuService
  13. from backend.models import Admin, AdminRole
  14. from django.core.cache import cache
  15. class AdminService:
  16. # 获取管理员信息
  17. @staticmethod
  18. def getAdminInfo(request):
  19. adminId = request.POST.get('id')
  20. adminInfo = Admin.objects.filter(id=adminId).first()
  21. if adminInfo is not None:
  22. return success(AdminService.getAdminDetail(adminInfo))
  23. else:
  24. return fail("管理员信息不存在")
  25. # return success(Admin.objects.filter(pk=request.POST.get('id', 0)).first())
  26. # 输出
  27. @staticmethod
  28. def getAdminDetail(admin: Admin):
  29. role = AdminRole.objects.filter(id=admin.role_id).first()
  30. roleInfo = {}
  31. if role:
  32. roleInfo = AdminRoleService.getDetail(role)
  33. #菜單
  34. results = AuthMenuService.menuInfo(admin.role_id)
  35. data = {
  36. 'id': admin.id,
  37. 'username': admin.username,
  38. 'email': admin.email,
  39. 'mobile': admin.mobile,
  40. 'realName': admin.real_name,
  41. 'role_id': admin.role_id,
  42. 'roleInfo': roleInfo,
  43. 'token': admin.token,
  44. 'createTime': admin.create_time,
  45. 'status': admin.status,
  46. 'avatar': admin.header,
  47. 'job': admin.job,
  48. 'code': admin.code,
  49. 'contact': admin.contact,
  50. 'introduction': '',
  51. 'roles': "[admin]",
  52. 'authList': results
  53. }
  54. return data
  55. # 创建管理员
  56. @staticmethod
  57. def create(request):
  58. form = UserForm(request.POST)
  59. if form.is_valid():
  60. form.instance.password = encrypt(form.instance.password)
  61. form.save()
  62. return success("保存成功")
  63. else:
  64. return fail(form.errors)
  65. @staticmethod
  66. def update(request):
  67. data = Admin.objects.filter(id=request.POST.get("id")).first()
  68. if data is not None:
  69. if request.POST.get("password"):
  70. data.password = encrypt(request.POST.get("password"))
  71. data.email = request.POST.get("email")
  72. data.mobile = request.POST.get("mobile")
  73. data.status = request.POST.get("status")
  74. data.real_name = request.POST.get("real_name")
  75. data.role_id = request.POST.get("role_id")
  76. data.code = request.POST.get("code")
  77. data.header = request.POST.get("header")
  78. data.job = request.POST.get("job")
  79. data.contact = request.POST.get("contact")
  80. data.save()
  81. return success("成功")
  82. else:
  83. return fail("更新用户信息失败")
  84. @staticmethod
  85. def updateProfile(request):
  86. data = AdminService.verify_token(request.POST.get("token"))
  87. if data is not None:
  88. data.email = request.POST.get("email")
  89. data.real_name = request.POST.get("realName")
  90. data.code = request.POST.get("code")
  91. data.header = request.POST.get("header")
  92. data.job = request.POST.get("job")
  93. data.contact = request.POST.get("contact")
  94. data.save()
  95. return success("成功")
  96. else:
  97. return fail("更新用户信息失败")
  98. @staticmethod
  99. def changePassword(request):
  100. oldPassword = request.POST.get("oldPassword")
  101. newPassword = request.POST.get("newPassword")
  102. confirmPassword = request.POST.get("confirmPassword")
  103. if newPassword!=confirmPassword:
  104. return fail("两次填写的密码不相同")
  105. data = AdminService.verify_token(request.POST.get("token"))
  106. if data is not None:
  107. if oldPassword != decrypt(data.password):
  108. return fail("原密码不正确")
  109. data.password=encrypt(newPassword)
  110. data.save()
  111. return success("成功")
  112. else:
  113. return fail("更新用户信息失败")
  114. # 通过token获取管理员信息
  115. @staticmethod
  116. def getAdminByToken(request):
  117. adminInfo = AdminService.verify_token(request.POST.get("token"))
  118. if adminInfo is not None:
  119. return success(AdminService.getAdminDetail(adminInfo))
  120. else:
  121. return fail("用户信息不存在")
  122. # 账户登录
  123. @staticmethod
  124. def login1(request):
  125. username = request.POST.get("username", "")
  126. password = request.POST.get("password", "")
  127. adminInfo = Admin.objects.filter(username=username).first()
  128. if adminInfo is not None:
  129. if password == decrypt(adminInfo.password):
  130. adminInfo.token = uuid.uuid4().hex
  131. adminInfo.save()
  132. return success({"token": adminInfo.token})
  133. else:
  134. return fail("登录密码不正确")
  135. else:
  136. return fail("登录失败,管理员用户名不存在")
  137. @staticmethod
  138. def login(request):
  139. username = request.POST.get("username", "")
  140. password = request.POST.get("password", "")
  141. adminInfo = Admin.objects.filter(username=username).first()
  142. if adminInfo is not None:
  143. if password == decrypt(adminInfo.password):
  144. # 检查是否存在有效的 token
  145. existing_token = AdminService.get_existing_token(adminInfo.id)
  146. if existing_token:
  147. # 如果存在有效的 token,直接返回
  148. return success({"token": existing_token})
  149. else:
  150. # 如果不存在有效的 token,生成新的
  151. new_token = uuid.uuid4().hex
  152. cache.set(f"admin_token:{new_token}", adminInfo.id, timeout=60 * 60 * 24)
  153. cache.set(f"admin_id_to_token:{adminInfo.id}", new_token, timeout=60 * 60 * 24)
  154. return success({"token": new_token})
  155. else:
  156. return fail("登录密码不正确")
  157. else:
  158. return fail("登录失败,管理员用户名不存在")
  159. @staticmethod
  160. def verify_token(token):
  161. admin_id = cache.get(f"admin_token:{token}")
  162. if admin_id:
  163. return Admin.objects.filter(id=admin_id).first()
  164. return None
  165. @staticmethod
  166. def get_existing_token(admin_id):
  167. # 尝试从缓存中获取该管理员的 token
  168. token = cache.get(f"admin_id_to_token:{admin_id}")
  169. if token:
  170. # 如果找到 token,检查它是否仍然有效
  171. if cache.get(f"admin_token:{token}"):
  172. return token
  173. return None
  174. # 账户登出
  175. @staticmethod
  176. def logout(request):
  177. token = request.POST.get("token")
  178. adminInfo = AdminService.verify_token(token)
  179. if adminInfo is not None:
  180. # Invalidate the token in the cache
  181. cache.delete(f"admin_token:{token}")
  182. cache.delete(f"admin_id_to_token:{adminInfo.id}")
  183. return success({"result": True})
  184. else:
  185. return fail("登出失败,token无效")
  186. # 搜索管理员列表
  187. @staticmethod
  188. def search(request):
  189. page = request.POST.get("page")
  190. pageSize = request.POST.get("pageSize")
  191. if page is None:
  192. page = 1
  193. if pageSize is None:
  194. pageSize = 1
  195. where = {}
  196. username = request.POST.get("username", '')
  197. if username:
  198. where["username__contains"] = username
  199. mobile = request.POST.get("mobile", '')
  200. if mobile:
  201. where["mobile__contains"] = mobile
  202. status = request.POST.get("status")
  203. if status:
  204. where['status'] = status
  205. paginator = Paginator(Admin.objects.filter(**where).exclude(status=4).order_by("-id"), pageSize) # 每页显示10条数据
  206. page_obj = paginator.get_page(page)
  207. dataList = []
  208. for item in page_obj:
  209. adminInfo = AdminService.getAdminDetail(item)
  210. dataList.append(adminInfo)
  211. return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))
  212. @staticmethod
  213. @transaction.atomic
  214. def delete(request):
  215. user_id = request.POST.get("id")
  216. if not user_id:
  217. return fail("User ID is required")
  218. try:
  219. # 尝试获取用户对象
  220. user = get_object_or_404(Admin, id=user_id)
  221. # 更新用户状态为逻辑删除(status=4)
  222. updated_count = Admin.objects.filter(id=user_id).update(status=4)
  223. if updated_count == 0:
  224. return fail("指定的用户不存在")
  225. return success("用户已成功删除")
  226. except ObjectDoesNotExist:
  227. return fail("指定的用户不存在")
  228. except Exception as e:
  229. return fail(f"删除用户时发生错误: {str(e)}")