ApplicationController.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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
  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. redirect_uri = request_dict.get("redirect_uri", '')
  64. client_secret = request_dict.get("client_secret", '')
  65. token = request_dict.get('token', None)
  66. # print("client_id", client_id)
  67. # print("state", state)
  68. # print("response_type", response_type)
  69. # print("scope", scope)
  70. # print("redirect_uri", redirect_uri)
  71. # print("client_secret", client_secret)
  72. tko = TokenObject(token)
  73. if tko.code == 0:
  74. userID = tko.userID
  75. nowTime = int(time.time())
  76. user_qs = GrantCodeModel.objects.filter(userID__userID=userID)
  77. code = CommonService.encrypt_data(randomlength=32)
  78. Application = ApplicationModel.objects.filter(client_id=client_id)
  79. if Application.exists():
  80. print(Application.exists())
  81. else:
  82. return JsonResponse({'error': 'config error,client_id This value is wrong'})
  83. if not user_qs.exists():
  84. print('在创建')
  85. try:
  86. grantcode = GrantCodeModel(
  87. userID=Device_User.objects.get(userID=userID),
  88. application=ApplicationModel.objects.get(client_id=client_id),
  89. code=code,
  90. expire_time=nowTime+3600,
  91. add_time=nowTime,
  92. update_time=nowTime)
  93. grantcode.save()
  94. except Exception as e:
  95. print(repr(e))
  96. return response.json(178)
  97. else:
  98. print('在修改')
  99. user_qs.update(code=code,update_time=nowTime,expire_time=nowTime+3600)
  100. redirect_uri = redirect_uri + '?code=' + code + '&state=' + state
  101. return response.json(0, {'url': redirect_uri})
  102. else:
  103. return response.json(tko.code)
  104. # 增加对code和client_id的校验代码,返回access_token和refresh_token
  105. def do_token(self,request_dict, response, content_range):
  106. code = request_dict.get("code", None)
  107. print('code:')
  108. print(code)
  109. str = content_range
  110. # str = 'Basic cHpiMTIzNDU2Nzg6cHpiMTIzNDU2Nzg='
  111. if str != '':
  112. str = str[6:]
  113. str = base64.b64decode(str)
  114. print(str)
  115. str = bytes.decode(str)
  116. print(type(str))
  117. str_all = str.split(":", 1)
  118. client_id = str_all[0]
  119. client_secret = str_all[1]
  120. eq = ApplicationModel.objects.filter(client_secret=client_secret)
  121. if eq.exists():
  122. access_token = code
  123. refresh_token = CommonService.encrypt_data(randomlength=32)
  124. res_json = {
  125. "access_token": access_token,
  126. "token_type": "bearer",
  127. "expires_in": 3600,
  128. "refresh_token": refresh_token,
  129. 'scope': 'cHpi'
  130. }
  131. print(res_json)
  132. return JsonResponse(res_json)
  133. else:
  134. return JsonResponse({'error': 'client_secret This value is misconfigured.'})
  135. else:
  136. return JsonResponse({'error': 'Check your configuration:no client_id,client_secret'})
  137. def do_user(self, request_dict, response,content_range):
  138. str = content_range
  139. # str = 'Bearer iBO4WssoK60eF4o6zm1e0fcHe2wRlRm1'
  140. if str != '':
  141. token = str[7:]
  142. code_qs = GrantCodeModel.objects.filter(code=token)
  143. if code_qs.exists():
  144. print(code_qs[0].userID_id)
  145. user_qs = Device_User.objects.filter(userID=code_qs[0].userID_id)
  146. # print(CommonService.qs_to_dict(user_qs)['datas'][0]['fields'])
  147. res_json = CommonService.qs_to_dict(user_qs)['datas'][0]['fields']
  148. res_json.pop('password')
  149. print(res_json)
  150. return JsonResponse(res_json)
  151. else:
  152. print('没有找到数据')
  153. return JsonResponse({'error': 'token inexistence'})
  154. else:
  155. return JsonResponse({'error': 'The request method is not correct. Please contact the administrator.'})
  156. class ApplicationView(View):
  157. def get(self, request, *args, **kwargs):
  158. request.encoding = 'utf-8'
  159. operation = kwargs.get('operation', None)
  160. return self.validation(request.GET, operation)
  161. def post(self, request, *args, **kwargs):
  162. request.encoding = 'utf-8'
  163. operation = kwargs.get('operation', None)
  164. return self.validation(request.POST, operation)
  165. def validation(self, request_dict, operation):
  166. response = ResponseObject()
  167. token = request_dict.get('token', None)
  168. tko = TokenObject(token)
  169. if tko.code == 0:
  170. userID = tko.userID
  171. if operation == 'query':
  172. return self.query(request_dict, userID, response)
  173. elif operation == 'add':
  174. return self.add(request_dict, userID, response)
  175. elif operation == 'update':
  176. return self.update(request_dict, userID, response)
  177. elif operation == 'delete':
  178. return self.delete(request_dict, userID, response)
  179. else:
  180. return response.json(414)
  181. else:
  182. return response.json(tko.code)
  183. def add(self, request_dict, userID, response):
  184. own_perm = ModelService.check_perm(userID=userID, permID=40)
  185. if own_perm is not True:
  186. return response.json(404)
  187. # 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
  188. nowTime = int(time.time())
  189. name = request_dict.get('name', None)
  190. client_id = request_dict.get('client_id', None)
  191. client_secret = request_dict.get('client_secret', None)
  192. client_type = request_dict.get('client_type', None)
  193. grant_type = request_dict.get('grant_type', None)
  194. redirect_uri = request_dict.get('redirect_uri', None)
  195. skip_auth = request_dict.get('skip_auth', None)
  196. try:
  197. ApplicationModel.objects.create(add_time=nowTime, update_time=nowTime, client_id=client_id, name=name, client_secret=client_secret,
  198. client_type=client_type,redirect_uri=redirect_uri,skip_auth=skip_auth,grant_type=grant_type)
  199. return response.json(0)
  200. except Exception:
  201. return response.json(178)
  202. def query(self, request_dict, userID, response):
  203. own_perm = ModelService.check_perm(userID, 20)
  204. if own_perm is True:
  205. page = int(request_dict.get('page', 0))
  206. line = int(request_dict.get('line', 0))
  207. if page == 0:
  208. page=1
  209. if line == 0:
  210. line=10
  211. qs = ApplicationModel.objects.all()
  212. gc = GrantCodeModel.objects.all()
  213. if qs.exists():
  214. count = qs.count()
  215. res = qs[(page - 1) * line:page * line]
  216. send_json = CommonService.qs_to_dict(res)
  217. send_json['count'] = count
  218. send_json['gc_count'] = gc.count()
  219. return response.json(0, send_json)
  220. else:
  221. return response.json(0, {'datas': [], 'count': 0})
  222. else:
  223. return response.json(404)
  224. # 管理员的编辑
  225. def update(self, request_dict, userID, response):
  226. own_perm = ModelService.check_perm(userID=userID, permID=50)
  227. if own_perm is not True:
  228. return response.json(404)
  229. deviceContent = request_dict.get('content', None)
  230. id = request_dict.get('id', None)
  231. if not deviceContent or not id:
  232. return response.json(444, 'content,id')
  233. try:
  234. timestamp = int(time.time())
  235. deviceData = json.loads(deviceContent)
  236. uid_set = ApplicationModel.objects.filter(id=id)
  237. if uid_set.exists():
  238. uid_set.update(update_time=timestamp, **deviceData)
  239. return response.json(0,{"update_time":timestamp})
  240. else:
  241. return response.json(173)
  242. except Exception:
  243. return response.json(177)
  244. def delete(self, request_dict, userID, response):
  245. own_perm = ModelService.check_perm(userID=userID, permID=10)
  246. if own_perm is not True:
  247. return response.json(404)
  248. id = request_dict.get('id', None)
  249. uid_set = ApplicationModel.objects.filter(id=id)
  250. if uid_set.exists():
  251. uid_set.delete()
  252. return response.json(0)
  253. else:
  254. return response.json(173)