AdminManage.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # -*- coding: utf-8 -*-
  2. from django.views.decorators.csrf import csrf_exempt
  3. from django.views.generic import TemplateView
  4. from django.utils.decorators import method_decorator
  5. from django.contrib.auth.hashers import make_password # 对密码加密模块
  6. from Service.TokenManager import JSONTokenManager
  7. from Model.models import Device_Info,Role
  8. from Service.ModelService import ModelService
  9. from django.utils import timezone
  10. import datetime
  11. from Model.models import Access_Log
  12. from Service.ResponseService import *
  13. from django.views.decorators.http import require_http_methods
  14. from Ansjer.config import *
  15. '''
  16. http://13.56.215.252:8222/adminManage/manage?operation=getAllDeviceArea&token=test
  17. http://13.56.215.252:8222/adminManage/manage?operation=getAllUserName&token=test
  18. http://13.56.215.252:8222/adminManage/manage?operation=getAllUID&token=test
  19. http://127.0.0.1:8000/adminManage/manage?operation=getAllOnLine&token=stest
  20. http://127.0.0.1:8000/adminManage/manage?operation=getOnLine&token=stest
  21. '''
  22. class AdminManage(TemplateView):
  23. @method_decorator(csrf_exempt)
  24. def dispatch(self, *args, **kwargs):
  25. return super(AdminManage, self).dispatch(*args, **kwargs)
  26. def get(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. return self.validation(request_dict=request.GET)
  29. def post(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. return self.validation(request_dict=request.POST)
  32. def validation(self, request_dict, *args, **kwargs):
  33. token = request_dict.get('token', None)
  34. if token is not None:
  35. tokenManager = JSONTokenManager()
  36. error_code = tokenManager.verify_AToken(token)
  37. if error_code == 0:
  38. userID = tokenManager.accessDict.get('userID', None)
  39. operation = request_dict.get('operation', None)
  40. param_flag = CommonService.get_param_flag(data=[userID, operation])
  41. if param_flag is True:
  42. if operation == 'resetUserPwd':
  43. return self.resetUserPwd(request_dict=request_dict, userID=userID)
  44. if operation == 'getAllOnLine':
  45. return self.getAllOnLine(userID=userID)
  46. if operation == 'getOnLine':
  47. return self.getOnLine(userID=userID)
  48. if operation == 'getAllUserName':
  49. return self.getAllUserName(userID=userID)
  50. if operation == 'getStatisAccess':
  51. return self.getStatisAccess(userID=userID,request_dict=request_dict)
  52. if operation == 'getAllUID':
  53. return self.getAllUID(userID=userID)
  54. if operation == 'getAllDeviceArea':
  55. return self.getAllDeviceArea(userID=userID)
  56. else:
  57. return ResponseJSON(444)
  58. else:
  59. return HttpResponse(tokenManager.errorCodeInfo(error_code))
  60. else:
  61. return ResponseJSON(311)
  62. def resetUserPwd(self, request_dict, userID):
  63. own_permission = ModelService.check_permission(userID=userID, permID=50)
  64. if own_permission is True:
  65. duserID = request_dict.get('duserID', None)
  66. userPwd = request_dict.get('userPwd', None)
  67. param_flag = CommonService.get_param_flag(data=[duserID])
  68. if param_flag is True:
  69. UserValid = Device_User.objects.filter(userID=duserID)
  70. if UserValid:
  71. if userPwd is None:
  72. userPwd = '123456'
  73. is_update = UserValid.update(password=make_password(userPwd))
  74. if is_update:
  75. return ResponseJSON(0)
  76. else:
  77. return ResponseJSON(106)
  78. else:
  79. return ResponseJSON(444)
  80. else:
  81. return ResponseJSON(404)
  82. def getAllUserName(self, userID):
  83. # 权限固定为30
  84. own_permission = ModelService.check_permission(userID=userID, permID=30)
  85. if own_permission is True:
  86. username_list = Device_User.objects.all().values_list('username', flat=True)
  87. if username_list:
  88. return ResponseJSON(0,{'username_list': list(username_list)})
  89. else:
  90. return ResponseJSON(0)
  91. else:
  92. return ResponseJSON(404)
  93. # 获取全部用户的在线个数
  94. def getAllOnLine(self, userID):
  95. # 权限固定为30
  96. own_permission = ModelService.check_permission(userID=userID, permID=30)
  97. if own_permission is True:
  98. allonline = Device_User.objects.all().values('online')
  99. # 两个变量,分别是在线,离线
  100. onlinenum = 0
  101. noonlinenum=0
  102. for q in allonline:
  103. if q['online'] ==True:
  104. onlinenum+=1
  105. else:
  106. noonlinenum+=1
  107. print("在线人数:")
  108. print(onlinenum)
  109. return ResponseJSON(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})
  110. else:
  111. return ResponseJSON(404)
  112. # 获取全部用户的在线人数
  113. def getOnLine(self, userID):
  114. # 权限固定为30
  115. own_permission = ModelService.check_permission(userID=userID, permID=30)
  116. if own_permission is True:
  117. online_list = Device_User.objects.all().values('online', 'last_login')
  118. # 两个变量,分别是在线,离线
  119. onlinenum=0
  120. noonlinenum=0
  121. for q in online_list:
  122. # print(q['last_login'] )
  123. # 最后访问时间加5分种
  124. dl_time = q['last_login'] + datetime.timedelta(minutes=OFF_LINE_TIME_DELTA)
  125. # print(dl_time)
  126. # 当前时间
  127. now_time = timezone.localtime(timezone.now())
  128. # print(now_time)
  129. # 如果当前时间大于最后访问的时间
  130. if now_time < dl_time:
  131. onlinenum += 1
  132. else:
  133. noonlinenum += 1
  134. print("在线人")
  135. print(onlinenum)
  136. return ResponseJSON(0, {"onlinenum": onlinenum,"no_onlinenum": noonlinenum})
  137. else:
  138. return ResponseJSON(404)
  139. # 获取所有设备地区
  140. def getAllDeviceArea(self, userID):
  141. own_permission = ModelService.check_permission(userID=userID, permID=30)
  142. if own_permission is True:
  143. qs = Device_Info.objects.all().values('area','UID')
  144. uid_area_dict = {}
  145. for q in qs:
  146. if q['UID'] and q['area']:
  147. uid_area_dict[q['UID']]=q['area']
  148. if len(uid_area_dict):
  149. area_dict = {}
  150. for k,v in uid_area_dict.items():
  151. if v in area_dict:
  152. area_dict[v] += 1
  153. else:
  154. area_dict[v] = 1
  155. return ResponseJSON(0,{'area':area_dict})
  156. else:
  157. return ResponseJSON(0)
  158. else:
  159. return ResponseJSON(404)
  160. '''
  161. 统计一天访问量
  162. http://192.168.136.45:8077/adminManage/manage?token=test&operation=getStatisAccess&timestamp=1528773308
  163. '''
  164. def getStatisAccess(self,userID,request_dict):
  165. own_permission = ModelService.check_permission(userID=userID, permID=30)
  166. if own_permission is True:
  167. time_stamp = int(request_dict.get('timestamp', None))
  168. times = datetime.datetime.fromtimestamp(time_stamp)
  169. time_dict = CommonService.getTimeDict(times)
  170. res = {}
  171. for k, v in time_dict.items():
  172. start_date = time_dict[k]
  173. end_date = time_dict[k] + datetime.timedelta(hours=1)
  174. count = Access_Log.objects.filter(time__range=(start_date, end_date)).count()
  175. if count:
  176. res[k] = count
  177. else:
  178. res[k] = 0
  179. return ResponseJSON(0, {'count': res})
  180. else:
  181. return ResponseJSON(404)
  182. def getAllUID(self,userID):
  183. own_permission = ModelService.check_permission(userID=userID, permID=30)
  184. if own_permission is True:
  185. uid_list = Device_Info.objects.all().values_list('UID', flat=True)
  186. if uid_list:
  187. return ResponseJSON(0, {'count': len(uid_list),'uid_list':list(uid_list)})
  188. else:
  189. return ResponseJSON(404)
  190. @csrf_exempt
  191. @require_http_methods(["GET"])
  192. def getUserIds(request):
  193. token = request.GET.get('token', None)
  194. if token is not None:
  195. tokenManager = JSONTokenManager()
  196. error_code = tokenManager.verify_AToken(token)
  197. if error_code == 0:
  198. userID = tokenManager.accessDict.get('userID', None)
  199. own_perm = ModelService.check_permission(userID,30)
  200. if own_perm is True:
  201. # userID_list = Device_User.objects.all().values_list('userID', flat=True)
  202. dn = Device_User.objects.all().values('userID', 'username')
  203. return ResponseJSON(0,{"datas":list(dn)})
  204. else:
  205. return ResponseJSON(404)
  206. else:
  207. return HttpResponse(tokenManager.errorCodeInfo(error_code))
  208. else:
  209. return ResponseJSON(311)
  210. @csrf_exempt
  211. # @require_http_methods(['GET'])
  212. def search_user_by_content(request):
  213. if request.method == 'GET':
  214. request_dict = request.GET
  215. if request.method == 'POST':
  216. request_dict = request.POST
  217. token = request_dict.get('token', None)
  218. page = request_dict.get('page', None)
  219. line = request_dict.get('line', None)
  220. content = request_dict.get('content', None)
  221. rstime = request_dict.get('rstime', None)
  222. retime = request_dict.get('retime', None)
  223. if page is not None and line is not None:
  224. page = int(page)
  225. line = int(line)
  226. else:
  227. return ResponseJSON(10,'page,line is none')
  228. if token is not None:
  229. tokenManager = JSONTokenManager()
  230. error_code = tokenManager.verify_AToken(token)
  231. if error_code == 0:
  232. userID = tokenManager.accessDict.get('userID', None)
  233. own_perm = ModelService.check_permission(userID,30)
  234. if own_perm is True:
  235. check_perm = ModelService.check_permission(userID=userID, permID=20)
  236. if check_perm is True:
  237. try:
  238. content = json.loads(content)
  239. search_kwargs = CommonService.get_kwargs(data=content)
  240. queryset = Device_User.objects.filter(**search_kwargs)
  241. except Exception as e:
  242. return ResponseJSON(444,repr(e))
  243. if rstime is not None and rstime != '' and retime is not None and retime != '':
  244. startt = datetime.datetime.fromtimestamp(int(rstime))
  245. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  246. endt = datetime.datetime.fromtimestamp(int(retime))
  247. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  248. queryset = queryset.filter(data_joined__range=(rstime, retime))
  249. elif rstime is not None and rstime != '':
  250. startt = datetime.datetime.fromtimestamp(int(rstime))
  251. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  252. queryset = queryset.filter(data_joined__gte=rstime)
  253. elif retime is not None and retime != '':
  254. endt = datetime.datetime.fromtimestamp(int(retime))
  255. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  256. queryset = queryset.filter(data_joined__lte=retime)
  257. if queryset.exists():
  258. count = queryset.count()
  259. res = queryset[(page - 1) * line:page * line]
  260. sqlDict = CommonService.query_set_to_dict(res)
  261. for k, v in enumerate(sqlDict["datas"]):
  262. if len(v['fields']['role']) > 0:
  263. role_query_set = Role.objects.get(rid=v['fields']['role'][0])
  264. sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
  265. for val in res:
  266. if v['pk'] == val.userID:
  267. if sqlDict["datas"][k]['fields']['online'] is True:
  268. dl_time = val.last_login + datetime.timedelta(minutes=5)
  269. now_time = timezone.localtime(timezone.now())
  270. if now_time > dl_time:
  271. sqlDict["datas"][k]['fields']['online'] = False
  272. sqlDict['count'] = count
  273. return ResponseJSON(0, sqlDict)
  274. return ResponseJSON(0, {'datas': [], 'count': 0})
  275. else:
  276. return ResponseJSON(404)
  277. else:
  278. return ResponseJSON(404)
  279. else:
  280. return HttpResponse(tokenManager.errorCodeInfo(error_code))
  281. else:
  282. return ResponseJSON(311)