UserController.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. if userEmail:
  159. identifyingCode = reds.get_data(key=userEmail + '_identifyingCode')
  160. if identifyingCode is False:
  161. return response.json(120)
  162. else:
  163. username = userEmail
  164. else:
  165. return response.json(120)
  166. if authCode != identifyingCode:
  167. return response.json(121)
  168. if dataValid.password_validate(password):
  169. if dataValid.email_validate(username):
  170. if userEmail:
  171. print(userEmail)
  172. emailValid = Device_User.objects.filter(userEmail=userEmail)
  173. if emailValid.exists():
  174. return response.json(103)
  175. if username:
  176. nameValid = Device_User.objects.filter(username=username)
  177. if nameValid.exists():
  178. return response.json(101)
  179. try:
  180. create_data = {
  181. "username": username,
  182. "userEmail": userEmail,
  183. "password": make_password(password),
  184. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  185. "is_active": True,
  186. "user_isValid": True,
  187. }
  188. users = Device_User.objects.create(**create_data)
  189. except Exception as e:
  190. errorInfo = traceback.format_exc()
  191. print(errorInfo)
  192. return response.json(424, repr(e))
  193. else:
  194. if reds.del_data(key=username + '_identifyingCode'):
  195. return response.json(0, {
  196. "user": {
  197. "userID": users.userID,
  198. "username": users.username,
  199. "userEmail": users.userEmail,
  200. "NickName": users.NickName,
  201. "userIconUrl": str(users.userIconUrl),
  202. "is_superuser": users.is_superuser,
  203. "is_active": users.is_active,
  204. "data_joined": date_handler(users.data_joined),
  205. "last_login": date_handler(users.last_login),
  206. }
  207. })
  208. else:
  209. return response.json(10, '删除缓存验证码错误')
  210. elif dataValid.mobile_validate(username):
  211. nameValid = Device_User.objects.filter(username=username)
  212. if nameValid:
  213. return response.json(101)
  214. try:
  215. create_data = {
  216. "username": username,
  217. "userEmail": userEmail,
  218. "password": make_password(password),
  219. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  220. "is_active": True,
  221. "user_isValid": True,
  222. }
  223. users = Device_User.objects.create(**create_data)
  224. except Exception as e:
  225. errorInfo = traceback.format_exc()
  226. print(errorInfo)
  227. return response.json(424, repr(e))
  228. else:
  229. if reds.del_data(key=username + '_identifyingCode'):
  230. return response.json(0, {
  231. "user": {
  232. "userID": users.userID,
  233. "username": users.username,
  234. "userEmail": users.userEmail,
  235. "NickName": users.NickName,
  236. "userIconUrl": str(users.userIconUrl),
  237. "is_superuser": users.is_superuser,
  238. "is_active": users.is_active,
  239. "data_joined": date_handler(users.data_joined),
  240. "last_login": date_handler(users.last_login),
  241. }
  242. })
  243. else:
  244. return response.json(10, '删除缓存验证码错误')
  245. else:
  246. return response.json(107)
  247. else:
  248. return response.json(109)
  249. # 登录
  250. class LoginView(TemplateView):
  251. @method_decorator(csrf_exempt) # @csrf_exempt
  252. def dispatch(self, *args, **kwargs):
  253. return super(LoginView, self).dispatch(*args, **kwargs)
  254. @ratelimit(key='ip', rate='5/m')
  255. def post(self, request, *args, **kwargs):
  256. request.encoding = 'utf-8'
  257. request_dict = request.POST
  258. language = request_dict.get('language', 'en')
  259. response = ResponseObject(language)
  260. was_limited = getattr(request, 'limited', False)
  261. if was_limited is True:
  262. return response.json(5)
  263. return self.validates(request_dict, response)
  264. @ratelimit(key='ip', rate='5/m')
  265. def get(self, request, *args, **kwargs):
  266. request.encoding = 'utf-8'
  267. request_dict = request.GET
  268. language = request_dict.get('language', 'en')
  269. response = ResponseObject(language)
  270. was_limited = getattr(request, 'limited', False)
  271. if was_limited is True:
  272. return response.json(5)
  273. return self.validates(request_dict, response)
  274. def validates(self, request_dict, response):
  275. username = request_dict.get('userName', None)
  276. password = request_dict.get('userPwd', None)
  277. print(username)
  278. print(password)
  279. mcode = request_dict.get('mobileMechanicalCode', '')
  280. if username and password:
  281. username = username.strip()
  282. password = password.strip()
  283. return self.login(username, password, mcode, response)
  284. else:
  285. return response.json(444, 'username,password')
  286. def login(self, username, password, mcode, response):
  287. dataValid = DataValid()
  288. if dataValid.mobile_validate(username):
  289. userValid = Device_User.objects.filter(username=username)
  290. if userValid:
  291. if userValid[0].user_isValid and userValid[0].is_active:
  292. c_p = check_password(password, userValid[0].password)
  293. if c_p:
  294. return self.LoginUpdate(userValid, mcode, response)
  295. else:
  296. return response.json(111)
  297. else:
  298. return response.json(110)
  299. else:
  300. return response.json(102)
  301. elif dataValid.email_validate(username):
  302. userValid = Device_User.objects.filter(userEmail=username)
  303. if userValid:
  304. if userValid[0].user_isValid and userValid[0].is_active:
  305. User = auth.authenticate(username=userValid[0].username, password=password)
  306. if User is not None:
  307. return self.LoginUpdate(userValid, mcode, response)
  308. else:
  309. return response.json(111)
  310. else:
  311. return response.json(110)
  312. else:
  313. return response.json(104)
  314. else:
  315. return response.json(104)
  316. def LoginUpdate(self, userValid, mcode, response):
  317. userID = userValid[0].userID
  318. print('userID'+userID)
  319. tko = TokenObject()
  320. res = tko.generate(data={'userID': userID, 'lang': response.lang, 'mcode': mcode})
  321. if tko.code == 0:
  322. now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
  323. userValid.update(last_login=now_time, online=True, machine_code=mcode, language=response.lang)
  324. role_dict = ModelService.own_role(userID=userID)
  325. res['rid'] = role_dict['rid']
  326. res['roleName'] = role_dict['roleName']
  327. res['permList'] = ModelService.own_permission(userID)
  328. res['userID'] = userID
  329. print(res)
  330. return response.json(0, res)
  331. else:
  332. return response.json(tko.code)
  333. # 登出
  334. class LogoutView(TemplateView):
  335. @method_decorator(csrf_exempt)
  336. def dispatch(self, *args, **kwargs):
  337. return super(LogoutView, self).dispatch(*args, **kwargs)
  338. def post(self, request, *args, **kwargs):
  339. request.encoding = 'utf-8'
  340. token = request.POST.get('token')
  341. return self.Logout(request, token)
  342. def get(self, request, *args, **kwargs):
  343. request.encoding = 'utf-8'
  344. token = request.GET.get('token')
  345. return self.Logout(request, token)
  346. def Logout(self, request, token):
  347. response = ResponseObject()
  348. if token:
  349. tko = TokenObject(token)
  350. tko.valid()
  351. if tko.code == 0:
  352. try:
  353. MiscellService.add_access_log(request=request, status_code=200)
  354. except Exception as e:
  355. pass
  356. is_udpate = Device_User.objects.filter(userID=tko.userID).update(online=False)
  357. if is_udpate:
  358. return response.json(0)
  359. else:
  360. return response.json(tko.code)
  361. else:
  362. return response.json(800)
  363. # 修改密码
  364. class ChangePwdView(TemplateView):
  365. @method_decorator(csrf_exempt)
  366. def dispatch(self, *args, **kwargs):
  367. return super(ChangePwdView, self).dispatch(*args, **kwargs)
  368. def post(self, request, *args, **kwargs):
  369. request.encoding = 'utf-8'
  370. request_dict = request.POST
  371. return self.validates(request_dict)
  372. def get(self, request, *args, **kwargs):
  373. request.encoding = 'gb2312'
  374. request_dict = request.GET
  375. return self.validates(request_dict)
  376. def validates(self, request_dict):
  377. token = request_dict.get('token', None)
  378. oldPwd = request_dict.get('oldPwd', None)
  379. newPwd = request_dict.get('newPwd', None)
  380. response = ResponseObject()
  381. if token and oldPwd and newPwd:
  382. tko = TokenObject(token)
  383. tko.valid()
  384. response.lang = tko.lang
  385. if tko.code == 0:
  386. return self.updatePwd(tko.userID, oldPwd, newPwd, response)
  387. else:
  388. return response.json(tko.code)
  389. else:
  390. return response.json(800)
  391. def updatePwd(self, userID, oldPwd, newPwd, response):
  392. user_qs = Device_User.objects.filter(userID=userID)
  393. if user_qs.exists():
  394. c_p = check_password(oldPwd, user_qs[0].password)
  395. if c_p:
  396. update = user_qs.update(password=make_password(newPwd))
  397. if update:
  398. return response.json(0)
  399. else:
  400. return response.json(112)
  401. else:
  402. return response.json(111)
  403. else:
  404. return response.json(113)
  405. class ForgetPwdView(TemplateView):
  406. '''
  407. 忘记密码
  408. '''
  409. @method_decorator(csrf_exempt)
  410. def dispatch(self, *args, **kwargs):
  411. return super(ForgetPwdView, self).dispatch(*args, **kwargs)
  412. @ratelimit(key='ip', rate='1/m')
  413. def get(self, request, *args, **kwargs):
  414. request.encoding = 'utf-8'
  415. response = ResponseObject()
  416. was_limited = getattr(request, 'limited', False)
  417. if was_limited is True:
  418. return response.json(5)
  419. userName = request.GET.get('userName', None)
  420. return self.ValidationError(userName, response)
  421. @ratelimit(key='ip', rate='1/m')
  422. def post(self, request):
  423. request.encoding = 'utf-8'
  424. userName = request.POST.get('userName', None)
  425. response = ResponseObject()
  426. was_limited = getattr(request, 'limited', False)
  427. if was_limited is True:
  428. return response.json(5)
  429. return self.ValidationError(userName,response)
  430. def ValidationError(self, userName, response):
  431. if userName != None:
  432. userName = userName.strip()
  433. return self.ForgetPwd(userName, response)
  434. else:
  435. return response.json(800)
  436. def ForgetPwd(self, userName, response):
  437. dataValid = DataValid()
  438. if dataValid.mobile_validate(userName):
  439. User = Device_User.objects.filter(username=userName)
  440. elif dataValid.email_validate(userName):
  441. User = Device_User.objects.filter(username=userName)
  442. else:
  443. return response.json(9)
  444. if User:
  445. email = User[0].userEmail
  446. userID = User[0].userID
  447. if email:
  448. redisObj = RedisObject()
  449. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  450. if reset_pwd is False:
  451. tko = TokenObject()
  452. rest = tko.generate(data={'userID': userID})
  453. token = rest['access_token']
  454. reset_pwd = CommonService.RandomStr(6)
  455. send_data = TemplateService.email_message(type='forget', language='en')
  456. reset_link = '{server_host}/account/email-re-pwd?token={token}'.format(
  457. server_host=SERVER_DOMAIN, token=token)
  458. send_body = send_data['body'].format(username=email, reset_pwd=reset_pwd, reset_link=reset_link)
  459. ses = SesClassObject()
  460. send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
  461. if send_res is True:
  462. if redisObj.set_data(key=userID + '_email_reset_pwd',val=reset_pwd,expire=3600):
  463. return response.json(0)
  464. else:
  465. return response.json(10, '存储验证失败')
  466. else:
  467. return response.json(89)
  468. else:
  469. return response.json(103)
  470. else:
  471. return response.json(9)
  472. class EmailResetPwdView(TemplateView):
  473. @method_decorator(csrf_exempt)
  474. def dispatch(self, *args, **kwargs):
  475. return super(EmailResetPwdView, self).dispatch(*args, **kwargs)
  476. # 查询
  477. def get(self, request, *args, **kwargs):
  478. response = ResponseObject()
  479. request_dict = request.GET
  480. return self.validate(request_dict, response, *args, **kwargs)
  481. # 认证登录
  482. def post(self, request, *args, **kwargs):
  483. response = ResponseObject()
  484. try:
  485. print(request.body.decode("utf-8"))
  486. json_data = json.loads(request.body.decode("utf-8"))
  487. except Exception as e:
  488. return response.json(10, repr(e))
  489. else:
  490. request_dict = json_data
  491. return self.validate(request_dict, response, *args, **kwargs)
  492. def validate(self, request_dict, response, *args, **kwargs):
  493. token = request_dict.get('token', None)
  494. if token is not None:
  495. tko = TokenObject(token)
  496. tko.valid()
  497. if tko.code == 0:
  498. redisObj = RedisObject()
  499. userID = tko.userID
  500. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  501. if reset_pwd is not False:
  502. user_qs = Device_User.objects.filter(userID=userID)
  503. if user_qs.exists():
  504. redisObj.del_data(key=userID + '_email_reset_pwd')
  505. is_update = user_qs.update(password=make_password(reset_pwd))
  506. if is_update:
  507. return HttpResponseRedirect("http://www.dvema.com/web/html/paw_update_success.html?code=" + reset_pwd)
  508. else:
  509. return response.json(10)
  510. else:
  511. return response.json(9)
  512. else:
  513. return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
  514. return response.json(306, 'rpwd')
  515. else:
  516. return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
  517. return response.json(tko.code)
  518. else:
  519. return response.json(444, 'token')
  520. class refreshTokenView(TemplateView):
  521. @method_decorator(csrf_exempt)
  522. def dispatch(self, *args, **kwargs):
  523. return super(refreshTokenView, self).dispatch(*args, **kwargs)
  524. def post(self, request, *args, **kwargs):
  525. request.encoding = 'utf-8'
  526. request_dict = json.loads(request.body.decode('utf-8'))
  527. return self.validation(request_dict)
  528. def get(self, request, *args, **kwargs):
  529. request.encoding = 'utf-8'
  530. request_dict = request.GET
  531. return self.validation(request_dict)
  532. def validation(self, request_dict):
  533. token = request_dict.get('token', None)
  534. lang = request_dict.get('lang', None)
  535. response = ResponseObject(lang)
  536. if token is not None:
  537. tko = TokenObject(token)
  538. res = tko.refresh()
  539. code = tko.code
  540. if code == 0:
  541. return response.json(0, res)
  542. else:
  543. return response.json(code)
  544. else:
  545. return response.json(444, 'token')