UserController.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2018/9/11 15:08
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: UserController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import traceback
  15. import simplejson as json
  16. from django.contrib import auth
  17. from django.contrib.auth.hashers import make_password, check_password # 对密码加密模块
  18. from django.http import HttpResponseRedirect
  19. from django.utils.decorators import method_decorator
  20. from django.utils.timezone import utc
  21. from django.views.decorators.csrf import csrf_exempt
  22. from django.views.generic import TemplateView
  23. from ratelimit.decorators import ratelimit
  24. from Ansjer.config import *
  25. from Controller.CheckUserData import DataValid, date_handler, RandomStr
  26. from Model.models import Device_User
  27. from Object.AWS.SesClassObject import SesClassObject
  28. from Object.RedisObject import RedisObject
  29. from Object.ResponseObject import ResponseObject
  30. from Object.TokenObject import TokenObject
  31. from Service.CommonService import CommonService
  32. from Service.MiscellService import MiscellService
  33. from Service.ModelService import ModelService
  34. from Service.TemplateService import TemplateService
  35. # 获取验证码
  36. class authCodeView(TemplateView):
  37. @method_decorator(csrf_exempt)
  38. def dispatch(self, *args, **kwargs):
  39. return super(authCodeView, self).dispatch(*args, **kwargs)
  40. @ratelimit(key='ip', rate='2/m')
  41. def post(self, request, *args, **kwargs):
  42. request.encoding = 'utf-8'
  43. lang = request.POST.get('language', None)
  44. response = ResponseObject(lang)
  45. was_limited = getattr(request, 'limited', False)
  46. if was_limited is True:
  47. return response.json(5)
  48. username = request.POST.get('userName', None)
  49. useremail = request.POST.get('userEmail', None)
  50. return self.ValidationError(username, useremail, response)
  51. # @ratelimit(key='ip', rate='2/m')
  52. def get(self, request, *args, **kwargs):
  53. # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
  54. request.encoding = 'utf-8'
  55. lang = request.GET.get('language', None)
  56. response = ResponseObject(lang)
  57. was_limited = getattr(request, 'limited', False)
  58. if was_limited is True:
  59. return response.json(5)
  60. username = request.GET.get('userName', None)
  61. email = request.GET.get('userEmail', None)
  62. return self.ValidationError(username, email, response)
  63. def ValidationError(self, username, email, response):
  64. if username:
  65. username = username.strip()
  66. return self.phoneCode(username, response)
  67. elif email:
  68. email = email.strip()
  69. return self.emailCode(email, response)
  70. else:
  71. return response.json(800)
  72. def phoneCode(self, phone, response):
  73. dataValid = DataValid()
  74. if dataValid.mobile_validate(phone):
  75. reds = RedisObject()
  76. identifyingCode = reds.get_data(key=phone + '_identifyingCode')
  77. if identifyingCode is False:
  78. user_qs = Device_User.objects.filter(username=phone)
  79. if user_qs.exists():
  80. return response.json(101)
  81. else:
  82. identifyingCode = RandomStr(6, True)
  83. if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=600):
  84. return response.json(0, {'identifyingCode': identifyingCode})
  85. else:
  86. return response.json(10, '生成缓存系统错误')
  87. else:
  88. return response.json(0, {'identifyingCode': identifyingCode})
  89. else:
  90. return response.json(107)
  91. def emailCode(self, email, response):
  92. dataValid = DataValid()
  93. if dataValid.email_validate(email):
  94. reds = RedisObject()
  95. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  96. if identifyingCode is False:
  97. user_qs = Device_User.objects.filter(username=email)
  98. email_qs = Device_User.objects.filter(userEmail=email)
  99. if user_qs.exists():
  100. return response.json(103)
  101. elif email_qs.exists():
  102. return response.json(103)
  103. else:
  104. identifyingCode = RandomStr(6, True)
  105. if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire):
  106. send_data = TemplateService.email_message(type='register_code', language=response.lang)
  107. ses = SesClassObject()
  108. send_res = ses.send_email(
  109. send_address_list=[email],
  110. subject=send_data['title'],
  111. body=send_data['body'].replace("{username}", email).replace("{captcha}",
  112. str(identifyingCode))
  113. )
  114. if send_res:
  115. reds.set_data(key=email + '_registerCode', val=identifyingCode, expire=AuthCode_Expire)
  116. return response.json(0, {'identifyingCode': identifyingCode})
  117. else:
  118. return response.json(44)
  119. else:
  120. return response.json(10, '生成缓存系统错误')
  121. else:
  122. return response.json(0, {'identifyingCode': identifyingCode})
  123. else:
  124. return response.json(107)
  125. # 验证码注册
  126. class registerView(TemplateView):
  127. @method_decorator(csrf_exempt)
  128. def dispatch(self, *args, **kwargs):
  129. return super(registerView, self).dispatch(*args, **kwargs)
  130. def post(self, request, *args, **kwargs):
  131. request.encoding = 'utf-8'
  132. request_dict = request.POST
  133. return self.validates(request_dict)
  134. def get(self, request, *args, **kwargs):
  135. request.encoding = 'utf-8'
  136. request_dict = request.GET
  137. return self.validates(request_dict)
  138. def validates(self, request_dict):
  139. username = request_dict.get('userName', None)
  140. userEmail = request_dict.get('userEmail', None)
  141. password = request_dict.get('userPwd', None)
  142. authCode = request_dict.get('identifyingCode', None)
  143. language = request_dict.get('language', None)
  144. response = ResponseObject(language)
  145. if username and password and authCode:
  146. # 过滤空格
  147. username = username.strip()
  148. if userEmail:
  149. userEmail = userEmail.strip()
  150. return self.register(username, userEmail, password, authCode, response)
  151. else:
  152. return response.json(800)
  153. def register(self, username, userEmail, password, authCode, response):
  154. dataValid = DataValid()
  155. reds = RedisObject()
  156. identifyingCode = reds.get_data(key=username + '_identifyingCode')
  157. if identifyingCode is False:
  158. identifyingCode = reds.get_data(key=userEmail + '_identifyingCode')
  159. if identifyingCode is False:
  160. return response.json(120)
  161. else:
  162. username = userEmail
  163. if authCode != identifyingCode:
  164. return response.json(121)
  165. if dataValid.password_validate(password):
  166. if dataValid.email_validate(username):
  167. nameValid = Device_User.objects.filter(username=username)
  168. emailValid = Device_User.objects.filter(userEmail=userEmail)
  169. if emailValid:
  170. return response.json(103)
  171. elif nameValid:
  172. return response.json(101)
  173. try:
  174. create_data = {
  175. "username": username,
  176. "userEmail": userEmail,
  177. "password": make_password(password),
  178. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  179. "is_active": True,
  180. "user_isValid": True,
  181. }
  182. users = Device_User.objects.create(**create_data)
  183. except Exception as e:
  184. errorInfo = traceback.format_exc()
  185. print(errorInfo)
  186. return response.json(424, repr(e))
  187. else:
  188. if reds.del_data(key=username + '_identifyingCode'):
  189. return response.json(0, {
  190. "user": {
  191. "userID": users.userID,
  192. "username": users.username,
  193. "userEmail": users.userEmail,
  194. "NickName": users.NickName,
  195. "userIconUrl": str(users.userIconUrl),
  196. "is_superuser": users.is_superuser,
  197. "is_active": users.is_active,
  198. "data_joined": date_handler(users.data_joined),
  199. "last_login": date_handler(users.last_login),
  200. }
  201. })
  202. else:
  203. return response.json(10, '删除缓存验证码错误')
  204. elif dataValid.mobile_validate(username):
  205. nameValid = Device_User.objects.filter(username=username)
  206. if nameValid:
  207. return response.json(101)
  208. try:
  209. create_data = {
  210. "username": username,
  211. "userEmail": userEmail,
  212. "password": make_password(password),
  213. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  214. "is_active": True,
  215. "user_isValid": True,
  216. }
  217. users = Device_User.objects.create(**create_data)
  218. except Exception as e:
  219. errorInfo = traceback.format_exc()
  220. print(errorInfo)
  221. return response.json(424, repr(e))
  222. else:
  223. if reds.del_data(key=username + '_identifyingCode'):
  224. return response.json(0, {
  225. "user": {
  226. "userID": users.userID,
  227. "username": users.username,
  228. "userEmail": users.userEmail,
  229. "NickName": users.NickName,
  230. "userIconUrl": str(users.userIconUrl),
  231. "is_superuser": users.is_superuser,
  232. "is_active": users.is_active,
  233. "data_joined": date_handler(users.data_joined),
  234. "last_login": date_handler(users.last_login),
  235. }
  236. })
  237. else:
  238. return response.json(10, '删除缓存验证码错误')
  239. else:
  240. return response.json(107)
  241. else:
  242. return response.json(109)
  243. # 登录
  244. class LoginView(TemplateView):
  245. @method_decorator(csrf_exempt) # @csrf_exempt
  246. def dispatch(self, *args, **kwargs):
  247. return super(LoginView, self).dispatch(*args, **kwargs)
  248. @ratelimit(key='ip', rate='5/m')
  249. def post(self, request, *args, **kwargs):
  250. request.encoding = 'utf-8'
  251. request_dict = request.POST
  252. language = request_dict.get('language', 'en')
  253. response = ResponseObject(language)
  254. was_limited = getattr(request, 'limited', False)
  255. if was_limited is True:
  256. return response.json(5)
  257. return self.validates(request_dict, response)
  258. @ratelimit(key='ip', rate='5/m')
  259. def get(self, request, *args, **kwargs):
  260. request.encoding = 'utf-8'
  261. request_dict = request.GET
  262. language = request_dict.get('language', 'en')
  263. response = ResponseObject(language)
  264. was_limited = getattr(request, 'limited', False)
  265. if was_limited is True:
  266. return response.json(5)
  267. return self.validates(request_dict, response)
  268. def validates(self, request_dict, response):
  269. username = request_dict.get('userName', None)
  270. password = request_dict.get('userPwd', None)
  271. mcode = request_dict.get('mobileMechanicalCode', '')
  272. if username and password:
  273. username = username.strip()
  274. password = password.strip()
  275. return self.login(username, password, mcode, response)
  276. else:
  277. return response.json(444, 'username,password')
  278. def login(self, username, password, mcode, response):
  279. dataValid = DataValid()
  280. if dataValid.mobile_validate(username):
  281. userValid = Device_User.objects.filter(username=username)
  282. if userValid:
  283. if userValid[0].user_isValid and userValid[0].is_active:
  284. c_p = check_password(password, userValid[0].password)
  285. if c_p:
  286. return self.LoginUpdate(userValid, mcode, response)
  287. else:
  288. return response.json(111)
  289. else:
  290. return response.json(110)
  291. else:
  292. return response.json(102)
  293. elif dataValid.email_validate(username):
  294. userValid = Device_User.objects.filter(userEmail=username)
  295. if userValid:
  296. if userValid[0].user_isValid and userValid[0].is_active:
  297. User = auth.authenticate(username=userValid[0].username, password=password)
  298. if User is not None:
  299. return self.LoginUpdate(userValid, mcode, response)
  300. else:
  301. return response.json(111)
  302. else:
  303. return response.json(110)
  304. else:
  305. return response.json(104)
  306. else:
  307. return response.json(104)
  308. def LoginUpdate(self, userValid, mcode, response):
  309. userID = userValid[0].userID
  310. print('userID'+userID)
  311. tko = TokenObject()
  312. res = tko.generate(data={'userID': userID, 'lang': response.lang, 'mcode': mcode})
  313. if tko.code == 0:
  314. now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
  315. userValid.update(last_login=now_time, online=True, machine_code=mcode, language=response.lang)
  316. role_dict = ModelService.own_role(userID=userID)
  317. res['rid'] = role_dict['rid']
  318. res['roleName'] = role_dict['roleName']
  319. res['permList'] = ModelService.own_permission(userID)
  320. res['userID'] = userID
  321. print(res)
  322. return response.json(0, res)
  323. else:
  324. return response.json(tko.code)
  325. # 登出
  326. class LogoutView(TemplateView):
  327. @method_decorator(csrf_exempt)
  328. def dispatch(self, *args, **kwargs):
  329. return super(LogoutView, self).dispatch(*args, **kwargs)
  330. def post(self, request, *args, **kwargs):
  331. request.encoding = 'utf-8'
  332. token = request.POST.get('token')
  333. return self.Logout(request, token)
  334. def get(self, request, *args, **kwargs):
  335. request.encoding = 'utf-8'
  336. token = request.GET.get('token')
  337. return self.Logout(request, token)
  338. def Logout(self, request, token):
  339. response = ResponseObject()
  340. if token:
  341. tko = TokenObject(token)
  342. tko.valid()
  343. if tko.code == 0:
  344. try:
  345. MiscellService.add_access_log(request=request, status_code=200)
  346. except Exception as e:
  347. pass
  348. is_udpate = Device_User.objects.filter(userID=tko.userID).update(online=False)
  349. if is_udpate:
  350. return response.json(0)
  351. else:
  352. return response.json(tko.code)
  353. else:
  354. return response.json(800)
  355. # 修改密码
  356. class ChangePwdView(TemplateView):
  357. @method_decorator(csrf_exempt)
  358. def dispatch(self, *args, **kwargs):
  359. return super(ChangePwdView, self).dispatch(*args, **kwargs)
  360. def post(self, request, *args, **kwargs):
  361. request.encoding = 'utf-8'
  362. request_dict = request.POST
  363. return self.validates(request_dict)
  364. def get(self, request, *args, **kwargs):
  365. request.encoding = 'gb2312'
  366. request_dict = request.GET
  367. return self.validates(request_dict)
  368. def validates(self, request_dict):
  369. token = request_dict.get('token', None)
  370. oldPwd = request_dict.get('oldPwd', None)
  371. newPwd = request_dict.get('newPwd', None)
  372. response = ResponseObject()
  373. if token and oldPwd and newPwd:
  374. tko = TokenObject(token)
  375. tko.valid()
  376. response.lang = tko.lang
  377. if tko.code == 0:
  378. return self.updatePwd(tko.userID, oldPwd, newPwd, response)
  379. else:
  380. return response.json(tko.code)
  381. else:
  382. return response.json(800)
  383. def updatePwd(self, userID, oldPwd, newPwd, response):
  384. user_qs = Device_User.objects.filter(userID=userID)
  385. if user_qs.exists():
  386. c_p = check_password(oldPwd, user_qs[0].password)
  387. if c_p:
  388. update = user_qs.update(password=make_password(newPwd))
  389. if update:
  390. return response.json(0)
  391. else:
  392. return response.json(112)
  393. else:
  394. return response.json(111)
  395. else:
  396. return response.json(113)
  397. class ForgetPwdView(TemplateView):
  398. '''
  399. 忘记密码
  400. '''
  401. __server_host = None
  402. @method_decorator(csrf_exempt)
  403. def dispatch(self, *args, **kwargs):
  404. return super(ForgetPwdView, self).dispatch(*args, **kwargs)
  405. @ratelimit(key='ip', rate='1/m')
  406. def get(self, request, *args, **kwargs):
  407. request.encoding = 'utf-8'
  408. self.__server_host = CommonService.req_path(request)
  409. response = ResponseObject()
  410. was_limited = getattr(request, 'limited', False)
  411. if was_limited is True:
  412. return response.json(5)
  413. userName = request.GET.get('userName', None)
  414. return self.ValidationError(userName, response)
  415. @ratelimit(key='ip', rate='1/m')
  416. def post(self, request):
  417. self.__server_host = CommonService.req_path(request)
  418. request.encoding = 'utf-8'
  419. userName = request.POST.get('userName', None)
  420. response = ResponseObject()
  421. was_limited = getattr(request, 'limited', False)
  422. if was_limited is True:
  423. return response.json(5)
  424. return self.ValidationError(userName,response)
  425. def ValidationError(self, userName, response):
  426. if userName != None:
  427. userName = userName.strip()
  428. return self.ForgetPwd(userName, response)
  429. else:
  430. return response.json(800)
  431. def ForgetPwd(self, userName, response):
  432. dataValid = DataValid()
  433. if dataValid.mobile_validate(userName):
  434. User = Device_User.objects.filter(username=userName)
  435. if dataValid.email_validate(userName):
  436. User = Device_User.objects.filter(username=userName)
  437. if User:
  438. email = User[0].userEmail
  439. userID = User[0].userID
  440. if email:
  441. redisObj = RedisObject()
  442. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  443. if reset_pwd is False:
  444. tko = TokenObject()
  445. rest = tko.generate(data={'userID': userID})
  446. token = rest['access_token']
  447. reset_pwd = CommonService.RandomStr(6)
  448. send_data = TemplateService.email_message(type='forget', language='en')
  449. reset_link = '{server_host}/account/email-re-pwd?token={token}'.format(
  450. server_host=self.__server_host, token=token)
  451. send_body = send_data['body'].format(username=email, reset_pwd=reset_pwd, reset_link=reset_link)
  452. ses = SesClassObject()
  453. send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
  454. if send_res is True:
  455. if redisObj.set_data(key=userID + '_email_reset_pwd',val=reset_pwd):
  456. return response.json(0)
  457. else:
  458. return response.json(10, '存储验证失败')
  459. else:
  460. return response.json(89)
  461. else:
  462. return response.json(103)
  463. else:
  464. return response.json(9)
  465. class EmailResetPwdView(TemplateView):
  466. @method_decorator(csrf_exempt)
  467. def dispatch(self, *args, **kwargs):
  468. return super(EmailResetPwdView, self).dispatch(*args, **kwargs)
  469. # 查询
  470. def get(self, request, *args, **kwargs):
  471. response = ResponseObject()
  472. request_dict = request.GET
  473. return self.validate(request_dict, response, *args, **kwargs)
  474. # 认证登录
  475. def post(self, request, *args, **kwargs):
  476. response = ResponseObject()
  477. try:
  478. print(request.body.decode("utf-8"))
  479. json_data = json.loads(request.body.decode("utf-8"))
  480. except Exception as e:
  481. return response.json(10, repr(e))
  482. else:
  483. request_dict = json_data
  484. return self.validate(request_dict, response, *args, **kwargs)
  485. def validate(self, request_dict, response, *args, **kwargs):
  486. token = request_dict.get('token', None)
  487. if token is not None:
  488. tko = TokenObject(token)
  489. tko.valid()
  490. if tko.code == 0:
  491. redisObj = RedisObject()
  492. userID = tko.userID
  493. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  494. if reset_pwd is not False:
  495. user_qs = Device_User.objects.filter(userID=userID)
  496. if user_qs.exists():
  497. redisObj.del_data(key=userID + '_email_reset_pwd')
  498. is_update = user_qs.update(password=make_password(reset_pwd))
  499. if is_update:
  500. return HttpResponseRedirect("http://www.dvema.com/web/html/paw_update_success.html?code=" + reset_pwd)
  501. else:
  502. return response.json(10)
  503. else:
  504. return response.json(9)
  505. else:
  506. return response.json(307, 'rpwd')
  507. else:
  508. return response.json(tko.code)
  509. else:
  510. return response.json(444, 'token')
  511. class refreshTokenView(TemplateView):
  512. @method_decorator(csrf_exempt)
  513. def dispatch(self, *args, **kwargs):
  514. return super(refreshTokenView, self).dispatch(*args, **kwargs)
  515. def post(self, request, *args, **kwargs):
  516. request.encoding = 'utf-8'
  517. request_dict = json.loads(request.body.decode('utf-8'))
  518. return self.validation(request_dict)
  519. def get(self, request, *args, **kwargs):
  520. request.encoding = 'utf-8'
  521. request_dict = request.GET
  522. return self.validation(request_dict)
  523. def validation(self, request_dict):
  524. token = request_dict.get('token', None)
  525. lang = request_dict.get('lang', None)
  526. response = ResponseObject(lang)
  527. if token is not None:
  528. tko = TokenObject(token)
  529. res = tko.refresh()
  530. code = tko.code
  531. if code == 0:
  532. return response.json(0, res)
  533. else:
  534. return response.json(code)
  535. else:
  536. return response.json(444, 'token')