ApplicationController.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD019
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2020/3/18 9:38
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: AppSetController.py
  12. @Contact: pzb3076@163.com
  13. """
  14. import requests
  15. import base64
  16. from Ansjer.config import SERVER_TYPE
  17. from Model.models import ApplicationModel, Device_User, GrantCodeModel
  18. from django.views.generic.base import View
  19. from Object.RedisObject import RedisObject
  20. from Object.TokenObject import TokenObject
  21. from Service.ModelService import ModelService
  22. from Service.CommonService import CommonService
  23. from django.http import JsonResponse, HttpResponseRedirect
  24. from django.contrib import auth
  25. import time,json
  26. from Object.ResponseObject import ResponseObject
  27. # http://192.168.136.39:8000/login/oauth/authorize
  28. # http://192.168.136.39:8000/application/query
  29. class AuthView(View):
  30. def get(self, request, *args, **kwargs):
  31. request.encoding = 'utf-8'
  32. operation = kwargs.get('operation', None)
  33. try:
  34. content_range = request.META['HTTP_AUTHORIZATION']
  35. print(content_range)
  36. except Exception as e:
  37. content_range = ''
  38. return self.validation(request.GET, operation, content_range)
  39. def post(self, request, *args, **kwargs):
  40. request.encoding = 'utf-8'
  41. operation = kwargs.get('operation', None)
  42. try:
  43. content_range = request.META['HTTP_AUTHORIZATION']
  44. print(content_range)
  45. except Exception as e:
  46. content_range = ''
  47. return self.validation(request.POST, operation, content_range)
  48. def validation(self, request_dict, operation, content_range):
  49. response = ResponseObject()
  50. if operation == 'authorize':
  51. return self.do_authorize(request_dict, response,content_range)
  52. elif operation == 'access_token':
  53. return self.do_token(request_dict, response, content_range)
  54. elif operation == 'user':
  55. return self.do_user(request_dict, response,content_range)
  56. else:
  57. return response.json(414)
  58. def do_authorize(self,request_dict, response, content_range):
  59. state = request_dict.get("state", '')
  60. client_id = request_dict.get("client_id", '')
  61. response_type = request_dict.get("response_type", '')
  62. scope = request_dict.get("scope", '')
  63. app_id = request_dict.get("app_id", '')
  64. redirect_uri = request_dict.get("redirect_uri", '')
  65. client_secret = request_dict.get("client_secret", '')
  66. token = request_dict.get('token', None)
  67. # print("client_id", client_id)
  68. # print("state", state)
  69. # print("response_type", response_type)
  70. # print("scope", scope)
  71. # print("redirect_uri", redirect_uri)
  72. # print("client_secret", client_secret)
  73. tko = TokenObject(token)
  74. if tko.code == 0:
  75. userID = tko.userID
  76. nowTime = int(time.time())
  77. user_qs = GrantCodeModel.objects.filter(userID__userID=userID)
  78. code = CommonService.encrypt_data(randomlength=32)
  79. application = ApplicationModel.objects.filter(client_id=client_id)
  80. if application.exists():
  81. print(application.exists())
  82. else:
  83. return response.json(10005)
  84. if application[0].redirect_uri != redirect_uri:
  85. return response.json(10006)
  86. if not user_qs.exists():
  87. print('在创建')
  88. try:
  89. grantcode = GrantCodeModel(
  90. userID=Device_User.objects.get(userID=userID),
  91. application=ApplicationModel.objects.get(client_id=client_id),
  92. code=code,
  93. app_id=app_id,
  94. expire_time=nowTime+3600,
  95. add_time=nowTime,
  96. update_time=nowTime)
  97. grantcode.save()
  98. except Exception as e:
  99. print(repr(e))
  100. return response.json(178)
  101. else:
  102. print('在修改')
  103. user_qs.update(code=code, app_id=app_id, update_time=nowTime, expire_time=nowTime+3600)
  104. redirect_uri = redirect_uri + '?code=' + code + '&state=' + state
  105. if application[0].skip_auth:
  106. return HttpResponseRedirect(redirect_uri)
  107. return response.json(0, {'url': redirect_uri})
  108. else:
  109. return response.json(tko.code)
  110. # 增加对code和client_id,client_secret的校验代码,返回access_token和refresh_token
  111. def do_token(self,request_dict, response, content_range):
  112. code = request_dict.get("code", None)
  113. print('code:')
  114. print(code)
  115. str = content_range
  116. # str = 'Basic cHpiMTIzNDU2Nzg6cHpiMTIzNDU2Nzg='
  117. if str != '':
  118. str = str[6:]
  119. str = base64.b64decode(str)
  120. print(str)
  121. str = bytes.decode(str)
  122. print(type(str))
  123. str_all = str.split(":", 1)
  124. client_id = str_all[0]
  125. client_secret = str_all[1]
  126. eq = ApplicationModel.objects.filter(client_secret=client_secret, client_id=client_id)
  127. if eq.exists():
  128. access_token = code
  129. refresh_token = CommonService.encrypt_data(randomlength=32)
  130. res_json = {
  131. "access_token": access_token,
  132. "token_type": "bearer",
  133. "expires_in": 3600,
  134. "refresh_token": refresh_token,
  135. 'scope': 'cHpi'
  136. }
  137. print(res_json)
  138. return JsonResponse(res_json)
  139. else:
  140. return response.json(10001)
  141. else:
  142. return response.json(10002)
  143. def do_user(self, request_dict, response,content_range):
  144. str = content_range
  145. # str = 'Bearer iBO4WssoK60eF4o6zm1e0fcHe2wRlRm1'
  146. if str != '':
  147. token = str[7:]
  148. code_qs = GrantCodeModel.objects.filter(code=token)
  149. if code_qs.exists():
  150. print(code_qs[0].userID_id)
  151. user_qs = Device_User.objects.filter(userID=code_qs[0].userID_id)
  152. # print(CommonService.qs_to_dict(user_qs)['datas'][0]['fields'])
  153. res_json = CommonService.qs_to_dict(user_qs)['datas'][0]['fields']
  154. res_json.pop('password')
  155. print(res_json)
  156. return JsonResponse(res_json)
  157. else:
  158. print('没有找到数据')
  159. return response.json(10003)
  160. else:
  161. return response.json(10004)
  162. class ApplicationView(View):
  163. def get(self, request, *args, **kwargs):
  164. request.encoding = 'utf-8'
  165. operation = kwargs.get('operation', None)
  166. return self.validation(request.GET, operation)
  167. def post(self, request, *args, **kwargs):
  168. request.encoding = 'utf-8'
  169. operation = kwargs.get('operation', None)
  170. return self.validation(request.POST, operation)
  171. def validation(self, request_dict, operation):
  172. response = ResponseObject()
  173. token = request_dict.get('token', None)
  174. tko = TokenObject(token)
  175. if tko.code == 0:
  176. userID = tko.userID
  177. if operation == 'query':
  178. return self.query(request_dict, userID, response)
  179. elif operation == 'add':
  180. return self.add(request_dict, userID, response)
  181. elif operation == 'update':
  182. return self.update(request_dict, userID, response)
  183. elif operation == 'delete':
  184. return self.delete(request_dict, userID, response)
  185. else:
  186. return response.json(414)
  187. else:
  188. return response.json(tko.code)
  189. def add(self, request_dict, userID, response):
  190. own_perm = ModelService.check_perm(userID=userID, permID=40)
  191. if own_perm is not True:
  192. return response.json(404)
  193. # http://192.168.136.39:8000/application/add?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxMzgwMDEzODAwMSIsImxhbmciOiJjbiIsInVzZXIiOiIxMzgwMDEzODAwMSIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImV4cCI6MTU4NzYxNjQ0NX0.BIwq - eWDcTnqLBTxqpi7BgJoU9TeIHC5Ibc2LUUJPls&name=pzb&client_id=pzb12345&client_secret=pzb12345678&client_type=confidential&grant_type=authorization_code&redirect_uri=https://www.zositech.cn&skip_auth=1
  194. nowTime = int(time.time())
  195. name = request_dict.get('name', None)
  196. client_id = request_dict.get('client_id', None)
  197. client_secret = request_dict.get('client_secret', None)
  198. client_type = request_dict.get('client_type', None)
  199. grant_type = request_dict.get('grant_type', None)
  200. redirect_uri = request_dict.get('redirect_uri', None)
  201. skip_auth = request_dict.get('skip_auth', None)
  202. try:
  203. ApplicationModel.objects.create(add_time=nowTime, update_time=nowTime, client_id=client_id, name=name, client_secret=client_secret,
  204. client_type=client_type,redirect_uri=redirect_uri,skip_auth=skip_auth,grant_type=grant_type)
  205. return response.json(0)
  206. except Exception:
  207. return response.json(178)
  208. def query(self, request_dict, userID, response):
  209. own_perm = ModelService.check_perm(userID, 20)
  210. if own_perm is True:
  211. page = int(request_dict.get('page', 0))
  212. line = int(request_dict.get('line', 0))
  213. if page == 0:
  214. page=1
  215. if line == 0:
  216. line=10
  217. qs = ApplicationModel.objects.all()
  218. gc = GrantCodeModel.objects.all()
  219. if qs.exists():
  220. count = qs.count()
  221. res = qs[(page - 1) * line:page * line]
  222. send_json = CommonService.qs_to_dict(res)
  223. send_json['count'] = count
  224. send_json['gc_count'] = gc.count()
  225. return response.json(0, send_json)
  226. else:
  227. return response.json(0, {'datas': [], 'count': 0})
  228. else:
  229. return response.json(404)
  230. # 管理员的编辑
  231. def update(self, request_dict, userID, response):
  232. own_perm = ModelService.check_perm(userID=userID, permID=50)
  233. if own_perm is not True:
  234. return response.json(404)
  235. deviceContent = request_dict.get('content', None)
  236. id = request_dict.get('id', None)
  237. if not deviceContent or not id:
  238. return response.json(444, 'content,id')
  239. try:
  240. timestamp = int(time.time())
  241. deviceData = json.loads(deviceContent)
  242. uid_set = ApplicationModel.objects.filter(id=id)
  243. if uid_set.exists():
  244. uid_set.update(update_time=timestamp, **deviceData)
  245. return response.json(0,{"update_time":timestamp})
  246. else:
  247. return response.json(173)
  248. except Exception:
  249. return response.json(177)
  250. def delete(self, request_dict, userID, response):
  251. own_perm = ModelService.check_perm(userID=userID, permID=10)
  252. if own_perm is not True:
  253. return response.json(404)
  254. id = request_dict.get('id', None)
  255. uid_set = ApplicationModel.objects.filter(id=id)
  256. if uid_set.exists():
  257. uid_set.delete()
  258. return response.json(0)
  259. else:
  260. return response.json(173)
  261. class GrantCodeView(View):
  262. def get(self, request, *args, **kwargs):
  263. request.encoding = 'utf-8'
  264. operation = kwargs.get('operation', None)
  265. return self.validation(request.GET, operation)
  266. def post(self, request, *args, **kwargs):
  267. request.encoding = 'utf-8'
  268. operation = kwargs.get('operation', None)
  269. return self.validation(request.POST, operation)
  270. def validation(self, request_dict, operation):
  271. response = ResponseObject()
  272. token = request_dict.get('token', None)
  273. tko = TokenObject(token)
  274. if tko.code == 0:
  275. userID = tko.userID
  276. if operation == 'query':
  277. return self.query(request_dict, userID, response)
  278. elif operation == 'delete':
  279. return self.delete(request_dict, userID, response)
  280. else:
  281. return response.json(414)
  282. else:
  283. return response.json(tko.code)
  284. def query(self, request_dict, userID, response):
  285. own_perm = ModelService.check_perm(userID, 20)
  286. if own_perm is True:
  287. page = int(request_dict.get('page', 0))
  288. line = int(request_dict.get('line', 0))
  289. if page == 0:
  290. page=1
  291. if line == 0:
  292. line=10
  293. gc = GrantCodeModel.objects.filter()
  294. if gc.exists():
  295. count = gc.count()
  296. res = gc[(page - 1) * line:page * line].values('id', 'userID', 'userID__username', 'userID__userEmail', 'userID__NickName', 'userID__language', 'userID__phone', 'code', 'app_id', 'application', 'add_time', 'update_time')
  297. send_json = CommonService.qs_to_list(res)
  298. return response.json(0, {'datas': send_json, 'count': count})
  299. else:
  300. return response.json(0, {'datas': [], 'count': 0})
  301. else:
  302. return response.json(404)
  303. def delete(self, request_dict, userID, response):
  304. own_perm = ModelService.check_perm(userID=userID, permID=10)
  305. if own_perm is not True:
  306. return response.json(404)
  307. id = request_dict.get('id', None)
  308. uid_set = GrantCodeModel.objects.filter(id=id)
  309. if uid_set.exists():
  310. uid_set.delete()
  311. return response.json(0)
  312. else:
  313. return response.json(173)