UserController.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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,datetime
  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 Controller.CheckUserData import DataValid, date_handler, RandomStr
  25. from Model.models import Device_User
  26. from Object.AWS.SesClassObject import SesClassObject
  27. from Object.RedisObject import RedisObject
  28. from Object.ResponseObject import ResponseObject
  29. from Object.TokenObject import TokenObject
  30. from Service.CommonService import CommonService
  31. from Service.MiscellService import MiscellService
  32. from Service.ModelService import ModelService
  33. from Service.TemplateService import TemplateService
  34. from Object.AliSmsObject import AliSmsObject
  35. from django.db.models import Q
  36. from Ansjer.config import AuthCode_Expire,SERVER_DOMAIN
  37. # 获取验证码
  38. class authCodeView(TemplateView):
  39. @method_decorator(csrf_exempt)
  40. def dispatch(self, *args, **kwargs):
  41. return super(authCodeView, self).dispatch(*args, **kwargs)
  42. @ratelimit(key='ip', rate='2/m')
  43. def post(self, request, *args, **kwargs):
  44. request.encoding = 'utf-8'
  45. lang = request.POST.get('language', None)
  46. response = ResponseObject(lang)
  47. was_limited = getattr(request, 'limited', False)
  48. if was_limited is True:
  49. return response.json(5)
  50. username = request.POST.get('userName', None)
  51. useremail = request.POST.get('userEmail', None)
  52. return self.ValidationError(username, useremail, response)
  53. # @ratelimit(key='ip', rate='2/m')
  54. def get(self, request, *args, **kwargs):
  55. # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
  56. request.encoding = 'utf-8'
  57. lang = request.GET.get('language', None)
  58. response = ResponseObject(lang)
  59. was_limited = getattr(request, 'limited', False)
  60. if was_limited is True:
  61. return response.json(5)
  62. username = request.GET.get('userName', None)
  63. email = request.GET.get('userEmail', None)
  64. return self.ValidationError(username, email, response)
  65. def ValidationError(self, username, email, response):
  66. if username:
  67. username = username.strip()
  68. return self.phoneCode(username, response)
  69. elif email:
  70. email = email.strip()
  71. return self.emailCode(email, response)
  72. else:
  73. return response.json(800)
  74. def phoneCode(self, phone, response):
  75. dataValid = DataValid()
  76. if dataValid.mobile_validate(phone):
  77. reds = RedisObject()
  78. identifyingCode = reds.get_data(key=phone + '_identifyingCode')
  79. if identifyingCode is False:
  80. user_qs = Device_User.objects.filter(username=phone)
  81. if user_qs.exists():
  82. return response.json(101)
  83. else:
  84. identifyingCode = RandomStr(6, True)
  85. if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=600):
  86. return response.json(0, {'identifyingCode': identifyingCode})
  87. else:
  88. return response.json(10, '生成缓存系统错误')
  89. else:
  90. return response.json(0, {'identifyingCode': identifyingCode})
  91. else:
  92. return response.json(107)
  93. def emailCode(self, email, response):
  94. dataValid = DataValid()
  95. if dataValid.email_validate(email):
  96. reds = RedisObject()
  97. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  98. if identifyingCode is False:
  99. user_qs = Device_User.objects.filter(username=email)
  100. email_qs = Device_User.objects.filter(userEmail=email)
  101. if user_qs.exists():
  102. return response.json(103)
  103. elif email_qs.exists():
  104. return response.json(103)
  105. else:
  106. identifyingCode = RandomStr(6, True)
  107. if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire):
  108. send_data = TemplateService.email_message(type='register_code', language=response.lang)
  109. ses = SesClassObject()
  110. send_res = ses.send_email(
  111. send_address_list=[email],
  112. subject=send_data['title'],
  113. body=send_data['body'].replace("{username}", email).replace("{captcha}",
  114. str(identifyingCode))
  115. )
  116. if send_res:
  117. reds.set_data(key=email + '_registerCode', val=identifyingCode, expire=AuthCode_Expire)
  118. return response.json(0, {'identifyingCode': identifyingCode})
  119. else:
  120. return response.json(44)
  121. else:
  122. return response.json(10, '生成缓存系统错误')
  123. else:
  124. return response.json(89, {'identifyingCode': identifyingCode})
  125. else:
  126. return response.json(107)
  127. # 验证码注册
  128. class registerView(TemplateView):
  129. @method_decorator(csrf_exempt)
  130. def dispatch(self, *args, **kwargs):
  131. return super(registerView, self).dispatch(*args, **kwargs)
  132. def post(self, request, *args, **kwargs):
  133. request.encoding = 'utf-8'
  134. request_dict = request.POST
  135. return self.validates(request_dict)
  136. def get(self, request, *args, **kwargs):
  137. request.encoding = 'utf-8'
  138. request_dict = request.GET
  139. return self.validates(request_dict)
  140. def validates(self, request_dict):
  141. username = request_dict.get('userName', None)
  142. userEmail = request_dict.get('userEmail', None)
  143. password = request_dict.get('userPwd', None)
  144. authCode = request_dict.get('identifyingCode', None)
  145. language = request_dict.get('language', None)
  146. response = ResponseObject(language)
  147. if username and password and authCode:
  148. # 过滤空格
  149. username = username.strip()
  150. if userEmail:
  151. userEmail = userEmail.strip()
  152. return self.register(username, userEmail, password, authCode, response)
  153. else:
  154. return response.json(800)
  155. def register(self, username, userEmail, password, authCode, response):
  156. dataValid = DataValid()
  157. reds = RedisObject()
  158. identifyingCode = reds.get_data(key=username + '_identifyingCode')
  159. if identifyingCode is False:
  160. if userEmail:
  161. identifyingCode = reds.get_data(key=userEmail + '_identifyingCode')
  162. if identifyingCode is False:
  163. return response.json(120)
  164. else:
  165. username = userEmail
  166. else:
  167. return response.json(120)
  168. if authCode != identifyingCode:
  169. return response.json(121)
  170. if dataValid.password_validate(password):
  171. if dataValid.email_validate(username):
  172. if userEmail:
  173. print(userEmail)
  174. emailValid = Device_User.objects.filter(userEmail=userEmail)
  175. if emailValid.exists():
  176. return response.json(103)
  177. else:
  178. userEmail = username
  179. if username:
  180. nameValid = Device_User.objects.filter(username=username)
  181. if nameValid.exists():
  182. return response.json(101)
  183. try:
  184. create_data = {
  185. "username": username,
  186. "userEmail": userEmail,
  187. "password": make_password(password),
  188. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  189. "is_active": True,
  190. "user_isValid": True,
  191. }
  192. users = Device_User.objects.create(**create_data)
  193. except Exception as e:
  194. errorInfo = traceback.format_exc()
  195. print(errorInfo)
  196. return response.json(424, repr(e))
  197. else:
  198. if reds.del_data(key=username + '_identifyingCode'):
  199. return response.json(0, {
  200. "user": {
  201. "userID": users.userID,
  202. "username": users.username,
  203. "userEmail": users.userEmail,
  204. "NickName": users.NickName,
  205. "userIconUrl": str(users.userIconUrl),
  206. "is_superuser": users.is_superuser,
  207. "is_active": users.is_active,
  208. "data_joined": date_handler(users.data_joined),
  209. "last_login": date_handler(users.last_login),
  210. }
  211. })
  212. else:
  213. return response.json(10, '删除缓存验证码错误')
  214. elif dataValid.mobile_validate(username):
  215. nameValid = Device_User.objects.filter(username=username)
  216. if nameValid:
  217. return response.json(101)
  218. try:
  219. create_data = {
  220. "username": username,
  221. "userEmail": userEmail,
  222. "password": make_password(password),
  223. "userID": CommonService.getUserID(μs=False, setOTAID=True),
  224. "is_active": True,
  225. "user_isValid": True,
  226. }
  227. users = Device_User.objects.create(**create_data)
  228. except Exception as e:
  229. errorInfo = traceback.format_exc()
  230. print(errorInfo)
  231. return response.json(424, repr(e))
  232. else:
  233. if reds.del_data(key=username + '_identifyingCode'):
  234. return response.json(0, {
  235. "user": {
  236. "userID": users.userID,
  237. "username": users.username,
  238. "userEmail": users.userEmail,
  239. "NickName": users.NickName,
  240. "userIconUrl": str(users.userIconUrl),
  241. "is_superuser": users.is_superuser,
  242. "is_active": users.is_active,
  243. "data_joined": date_handler(users.data_joined),
  244. "last_login": date_handler(users.last_login),
  245. }
  246. })
  247. else:
  248. return response.json(10, '删除缓存验证码错误')
  249. else:
  250. return response.json(107)
  251. else:
  252. return response.json(109)
  253. # 登录
  254. class LoginView(TemplateView):
  255. @method_decorator(csrf_exempt) # @csrf_exempt
  256. def dispatch(self, *args, **kwargs):
  257. return super(LoginView, self).dispatch(*args, **kwargs)
  258. @ratelimit(key='ip', rate='5/m')
  259. def post(self, request, *args, **kwargs):
  260. request.encoding = 'utf-8'
  261. request_dict = request.POST
  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. @ratelimit(key='ip', rate='5/m')
  269. def get(self, request, *args, **kwargs):
  270. request.encoding = 'utf-8'
  271. request_dict = request.GET
  272. language = request_dict.get('language', 'en')
  273. response = ResponseObject(language)
  274. was_limited = getattr(request, 'limited', False)
  275. if was_limited is True:
  276. return response.json(5)
  277. return self.validates(request_dict, response)
  278. def validates(self, request_dict, response):
  279. username = request_dict.get('userName', None)
  280. password = request_dict.get('userPwd', None)
  281. print(username)
  282. print(password)
  283. mcode = request_dict.get('mobileMechanicalCode', '')
  284. if username and password:
  285. username = username.strip()
  286. password = password.strip()
  287. return self.login(username, password, mcode, response)
  288. else:
  289. return response.json(444, 'username,password')
  290. def login(self, username, password, mcode, response):
  291. dataValid = DataValid()
  292. if dataValid.mobile_validate(username):
  293. userValid = Device_User.objects.filter(username=username)
  294. if userValid:
  295. if userValid[0].user_isValid and userValid[0].is_active:
  296. c_p = check_password(password, userValid[0].password)
  297. if c_p:
  298. return self.LoginUpdate(userValid, mcode, response)
  299. else:
  300. return response.json(111)
  301. else:
  302. return response.json(110)
  303. else:
  304. return response.json(102)
  305. elif dataValid.email_validate(username):
  306. userValid = Device_User.objects.filter(userEmail=username)
  307. if userValid:
  308. if userValid[0].user_isValid and userValid[0].is_active:
  309. User = auth.authenticate(username=userValid[0].username, password=password)
  310. if User is not None:
  311. return self.LoginUpdate(userValid, mcode, response)
  312. else:
  313. return response.json(111)
  314. else:
  315. return response.json(110)
  316. else:
  317. return response.json(104)
  318. else:
  319. return response.json(104)
  320. def LoginUpdate(self, userValid, mcode, response):
  321. userID = userValid[0].userID
  322. print('userID' + userID)
  323. tko = TokenObject()
  324. res = tko.generate(data={'userID': userID, 'lang': response.lang, 'mcode': mcode})
  325. if tko.code == 0:
  326. now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
  327. userValid.update(last_login=now_time, online=True, machine_code=mcode, language=response.lang)
  328. role_dict = ModelService.own_role(userID=userID)
  329. res['rid'] = role_dict['rid']
  330. res['roleName'] = role_dict['roleName']
  331. res['permList'] = ModelService.own_permission(userID)
  332. res['userID'] = userID
  333. print(res)
  334. return response.json(0, res)
  335. else:
  336. return response.json(tko.code)
  337. # 登出
  338. class LogoutView(TemplateView):
  339. @method_decorator(csrf_exempt)
  340. def dispatch(self, *args, **kwargs):
  341. return super(LogoutView, self).dispatch(*args, **kwargs)
  342. def post(self, request, *args, **kwargs):
  343. request.encoding = 'utf-8'
  344. token = request.POST.get('token')
  345. return self.Logout(request, token)
  346. def get(self, request, *args, **kwargs):
  347. request.encoding = 'utf-8'
  348. token = request.GET.get('token')
  349. return self.Logout(request, token)
  350. def Logout(self, request, token):
  351. response = ResponseObject()
  352. if token:
  353. tko = TokenObject(token)
  354. tko.valid()
  355. if tko.code == 0:
  356. try:
  357. MiscellService.add_access_log(request=request, status_code=200)
  358. except Exception as e:
  359. pass
  360. is_udpate = Device_User.objects.filter(userID=tko.userID).update(online=False)
  361. if is_udpate:
  362. return response.json(0)
  363. else:
  364. return response.json(tko.code)
  365. else:
  366. return response.json(800)
  367. # 修改密码
  368. class ChangePwdView(TemplateView):
  369. @method_decorator(csrf_exempt)
  370. def dispatch(self, *args, **kwargs):
  371. return super(ChangePwdView, self).dispatch(*args, **kwargs)
  372. def post(self, request, *args, **kwargs):
  373. request.encoding = 'utf-8'
  374. request_dict = request.POST
  375. return self.validates(request_dict)
  376. def get(self, request, *args, **kwargs):
  377. request.encoding = 'gb2312'
  378. request_dict = request.GET
  379. return self.validates(request_dict)
  380. def validates(self, request_dict):
  381. token = request_dict.get('token', None)
  382. oldPwd = request_dict.get('oldPwd', None)
  383. newPwd = request_dict.get('newPwd', None)
  384. response = ResponseObject()
  385. if token and oldPwd and newPwd:
  386. tko = TokenObject(token)
  387. tko.valid()
  388. response.lang = tko.lang
  389. if tko.code == 0:
  390. return self.updatePwd(tko.userID, oldPwd, newPwd, response)
  391. else:
  392. return response.json(tko.code)
  393. else:
  394. return response.json(800)
  395. def updatePwd(self, userID, oldPwd, newPwd, response):
  396. user_qs = Device_User.objects.filter(userID=userID)
  397. if user_qs.exists():
  398. c_p = check_password(oldPwd, user_qs[0].password)
  399. if c_p:
  400. update = user_qs.update(password=make_password(newPwd))
  401. if update:
  402. return response.json(0)
  403. else:
  404. return response.json(112)
  405. else:
  406. return response.json(111)
  407. else:
  408. return response.json(113)
  409. class ForgetPwdView(TemplateView):
  410. '''
  411. 忘记密码
  412. '''
  413. @method_decorator(csrf_exempt)
  414. def dispatch(self, *args, **kwargs):
  415. return super(ForgetPwdView, self).dispatch(*args, **kwargs)
  416. @ratelimit(key='ip', rate='1/m')
  417. def get(self, request, *args, **kwargs):
  418. request.encoding = 'utf-8'
  419. response = ResponseObject()
  420. was_limited = getattr(request, 'limited', False)
  421. if was_limited is True:
  422. return response.json(5)
  423. userName = request.GET.get('userName', None)
  424. return self.ValidationError(userName, response)
  425. @ratelimit(key='ip', rate='1/m')
  426. def post(self, request):
  427. request.encoding = 'utf-8'
  428. userName = request.POST.get('userName', None)
  429. response = ResponseObject()
  430. was_limited = getattr(request, 'limited', False)
  431. if was_limited is True:
  432. return response.json(5)
  433. return self.ValidationError(userName, response)
  434. def ValidationError(self, userName, response):
  435. if userName != None:
  436. userName = userName.strip()
  437. return self.ForgetPwd(userName, response)
  438. else:
  439. return response.json(800)
  440. def ForgetPwd(self, userName, response):
  441. dataValid = DataValid()
  442. if dataValid.mobile_validate(userName):
  443. User = Device_User.objects.filter(username=userName)
  444. elif dataValid.email_validate(userName):
  445. User = Device_User.objects.filter(username=userName)
  446. if not User.exists():
  447. User = Device_User.objects.filter(userEmail=userName)
  448. else:
  449. return response.json(9)
  450. if User:
  451. email = User[0].userEmail
  452. userID = User[0].userID
  453. if email:
  454. redisObj = RedisObject()
  455. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  456. if reset_pwd is False:
  457. tko = TokenObject()
  458. rest = tko.generate(data={'userID': userID})
  459. token = rest['access_token']
  460. reset_pwd = CommonService.RandomStr(6)
  461. send_data = TemplateService.email_message(type='forget', language='en')
  462. reset_link = '{server_host}/account/email-re-pwd?token={token}'.format(
  463. server_host=SERVER_DOMAIN, token=token)
  464. send_body = send_data['body'].format(username=email, reset_pwd=reset_pwd, reset_link=reset_link)
  465. ses = SesClassObject()
  466. send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
  467. if send_res is True:
  468. if redisObj.set_data(key=userID + '_email_reset_pwd', val=reset_pwd, expire=3600):
  469. return response.json(0)
  470. else:
  471. return response.json(10, '存储验证失败')
  472. else:
  473. return response.json(89)
  474. else:
  475. return response.json(103)
  476. else:
  477. return response.json(9)
  478. class EmailResetPwdView(TemplateView):
  479. @method_decorator(csrf_exempt)
  480. def dispatch(self, *args, **kwargs):
  481. return super(EmailResetPwdView, self).dispatch(*args, **kwargs)
  482. # 查询
  483. def get(self, request, *args, **kwargs):
  484. response = ResponseObject()
  485. request_dict = request.GET
  486. return self.validate(request_dict, response, *args, **kwargs)
  487. # 认证登录
  488. def post(self, request, *args, **kwargs):
  489. response = ResponseObject()
  490. try:
  491. print(request.body.decode("utf-8"))
  492. json_data = json.loads(request.body.decode("utf-8"))
  493. except Exception as e:
  494. return response.json(10, repr(e))
  495. else:
  496. request_dict = json_data
  497. return self.validate(request_dict, response, *args, **kwargs)
  498. def validate(self, request_dict, response, *args, **kwargs):
  499. token = request_dict.get('token', None)
  500. if token is not None:
  501. tko = TokenObject(token)
  502. tko.valid()
  503. if tko.code == 0:
  504. redisObj = RedisObject()
  505. userID = tko.userID
  506. reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
  507. if reset_pwd is not False:
  508. user_qs = Device_User.objects.filter(userID=userID)
  509. if user_qs.exists():
  510. redisObj.del_data(key=userID + '_email_reset_pwd')
  511. is_update = user_qs.update(password=make_password(reset_pwd))
  512. if is_update:
  513. return HttpResponseRedirect(
  514. "http://www.dvema.com/web/html/paw_update_success.html?code=" + reset_pwd)
  515. else:
  516. return response.json(10)
  517. else:
  518. return response.json(9)
  519. else:
  520. return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
  521. return response.json(306, 'rpwd')
  522. else:
  523. return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
  524. return response.json(tko.code)
  525. else:
  526. return response.json(444, 'token')
  527. class refreshTokenView(TemplateView):
  528. @method_decorator(csrf_exempt)
  529. def dispatch(self, *args, **kwargs):
  530. return super(refreshTokenView, self).dispatch(*args, **kwargs)
  531. def post(self, request, *args, **kwargs):
  532. request.encoding = 'utf-8'
  533. request_dict = json.loads(request.body.decode('utf-8'))
  534. return self.validation(request_dict)
  535. def get(self, request, *args, **kwargs):
  536. request.encoding = 'utf-8'
  537. request_dict = request.GET
  538. return self.validation(request_dict)
  539. def validation(self, request_dict):
  540. token = request_dict.get('token', None)
  541. lang = request_dict.get('lang', None)
  542. response = ResponseObject(lang)
  543. if token is not None:
  544. tko = TokenObject(token)
  545. res = tko.refresh()
  546. code = tko.code
  547. if code == 0:
  548. return response.json(0, res)
  549. else:
  550. return response.json(code)
  551. else:
  552. return response.json(444, 'token')
  553. # 获取验证码
  554. class v2authCodeView(TemplateView):
  555. @method_decorator(csrf_exempt)
  556. def dispatch(self, *args, **kwargs):
  557. return super(v2authCodeView, self).dispatch(*args, **kwargs)
  558. @ratelimit(key='ip', rate='2/m')
  559. def post(self, request, *args, **kwargs):
  560. request.encoding = 'utf-8'
  561. lang = request.POST.get('lang', None)
  562. response = ResponseObject(lang)
  563. was_limited = getattr(request, 'limited', False)
  564. if was_limited is True:
  565. return response.json(5)
  566. request_dict = request.POST
  567. return self.ValidationError(request_dict, response)
  568. @ratelimit(key='ip', rate='2/m')
  569. def get(self, request, *args, **kwargs):
  570. # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
  571. request.encoding = 'utf-8'
  572. lang = request.GET.get('lang', None)
  573. response = ResponseObject(lang)
  574. was_limited = getattr(request, 'limited', False)
  575. if was_limited is True:
  576. return response.json(5)
  577. request_dict = request.GET
  578. return self.ValidationError(request_dict, response)
  579. def ValidationError(self, request_dict, response):
  580. email = request_dict.get('email', None)
  581. phone = request_dict.get('phone', None)
  582. if email is not None:
  583. email = email.strip()
  584. return self.emailCode(email, response)
  585. elif phone is not None:
  586. phone = phone.strip()
  587. return self.phoneCode(phone, response)
  588. else:
  589. return response.json(444)
  590. def emailCode(self, email, response):
  591. dataValid = DataValid()
  592. # 邮箱匹配
  593. if dataValid.email_validate(email) is False:
  594. return response.json(107)
  595. reds = RedisObject()
  596. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  597. # 是否以获取邮箱验证码
  598. if identifyingCode is True:
  599. return response.json(89)
  600. user_qs = Device_User.objects.filter(username=email)
  601. email_qs = Device_User.objects.filter(userEmail=email)
  602. # 邮箱用户是否已存在
  603. if user_qs.exists():
  604. return response.json(103)
  605. elif email_qs.exists():
  606. return response.json(103)
  607. # 生成随机6位数
  608. identifyingCode = RandomStr(6, True)
  609. # 设置随机数缓存生命周期
  610. if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire) is not True:
  611. return response.json(10, '生成缓存系统错误')
  612. send_data = TemplateService.email_message(type='register_code', language=response.lang)
  613. ses = SesClassObject()
  614. # 发送邮件
  615. send_res = ses.send_email(
  616. send_address_list=[email],
  617. subject=send_data['title'],
  618. body=send_data['body'].replace("{username}", email).replace("{captcha}",
  619. str(identifyingCode))
  620. )
  621. if send_res is not True:
  622. return response.json(44)
  623. reds.set_data(key=email + '_registerCode', val=identifyingCode, expire=AuthCode_Expire)
  624. return response.json(0, {'identifyingCode': identifyingCode})
  625. def phoneCode(self, phone, response):
  626. dataValid = DataValid()
  627. if dataValid.mobile_validate(phone) is not True:
  628. return response.json(107)
  629. reds = RedisObject()
  630. identifyingCode = reds.get_data(key=phone + '_identifyingCode')
  631. if identifyingCode:
  632. return response.json(90)
  633. user_qs = Device_User.objects.filter(username=phone)
  634. phone_qs = Device_User.objects.filter(phone=phone)
  635. if user_qs.exists() or phone_qs.exists():
  636. return response.json(101)
  637. identifyingCode = RandomStr(6, True)
  638. if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=300) is not True:
  639. return response.json(10, '生成缓存系统错误')
  640. # 发送手机验证码
  641. aliSms = AliSmsObject()
  642. res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name='Ansjer',
  643. temp_msg='SMS_151600991')
  644. if res["Code"] == "OK":
  645. return response.json(0)
  646. # return response.json(0, {'identifyingCode': identifyingCode})
  647. else:
  648. return response.json(10, res["Message"])
  649. # 验证码注册
  650. class v2registerView(TemplateView):
  651. @method_decorator(csrf_exempt)
  652. def dispatch(self, *args, **kwargs):
  653. return super(v2registerView, self).dispatch(*args, **kwargs)
  654. def post(self, request, *args, **kwargs):
  655. request.encoding = 'utf-8'
  656. request_dict = request.POST
  657. return self.validates(request_dict)
  658. def get(self, request, *args, **kwargs):
  659. request.encoding = 'utf-8'
  660. request_dict = request.GET
  661. return self.validates(request_dict)
  662. def validates(self, request_dict):
  663. phone = request_dict.get('phone', None)
  664. email = request_dict.get('email', None)
  665. password = request_dict.get('password', None)
  666. authcode = request_dict.get('authcode', None)
  667. lang = request_dict.get('lang', None)
  668. response = ResponseObject(lang)
  669. if password is None:
  670. return response.json(444, 'password')
  671. if authcode is None:
  672. return response.json(444, 'identifyingCode')
  673. if phone is not None:
  674. return self.do_phone_register(phone, password, authcode, response)
  675. elif email is not None:
  676. return self.do_email_register(email, password, authcode, response)
  677. else:
  678. return response.json(444, 'phone or email')
  679. def do_phone_register(self, phone, password, authcode, response):
  680. data_valid = DataValid()
  681. if data_valid.mobile_validate(phone) is not True:
  682. return response.json(100)
  683. if data_valid.password_validate(password) is not True:
  684. return response.json(109)
  685. reds = RedisObject()
  686. identifyingCode = reds.get_data(key=phone + '_identifyingCode')
  687. # 判断验证码是否过期
  688. if identifyingCode is False:
  689. return response.json(120)
  690. # 验证码是否正确
  691. if authcode != identifyingCode:
  692. return response.json(121)
  693. phone_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
  694. # 是否已存在
  695. if phone_qs.exists():
  696. return response.json(101)
  697. try:
  698. users = Device_User.objects.create(
  699. phone=phone,
  700. password=password,
  701. userID=CommonService.getUserID(μs=False, setOTAID=True),
  702. is_active=True,
  703. user_isValid=True,
  704. )
  705. except Exception as e:
  706. errorInfo = traceback.format_exc()
  707. print(errorInfo)
  708. return response.json(424, repr(e))
  709. else:
  710. if not reds.del_data(key=phone + '_identifyingCode'):
  711. return response.json(10, '删除缓存验证码错误')
  712. return self.do_login(phone_qs, response)
  713. def do_login(self, user_qs, response):
  714. userID = user_qs[0].userID
  715. print('userID' + userID)
  716. tko = TokenObject()
  717. res = tko.generate(data={'userID': userID, 'lang': response.lang})
  718. if tko.code == 0:
  719. now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
  720. user_qs.update(last_login=now_time, online=True, language=response.lang)
  721. role_dict = ModelService.own_role(userID=userID)
  722. res['rid'] = role_dict['rid']
  723. res['roleName'] = role_dict['roleName']
  724. res['permList'] = ModelService.own_permission(userID)
  725. res['userID'] = userID
  726. print(res)
  727. return response.json(0, res)
  728. else:
  729. return response.json(tko.code)
  730. def do_email_register(self, email, password, authcode, response):
  731. data_valid = DataValid()
  732. if data_valid.email_validate(email) is not True:
  733. return response.json(105)
  734. if data_valid.password_validate(password) is not True:
  735. return response.json(109)
  736. reds = RedisObject()
  737. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  738. # 判断验证码是否过期
  739. if identifyingCode is False:
  740. return response.json(120)
  741. # 验证码是否正确
  742. if authcode != identifyingCode:
  743. return response.json(121)
  744. email_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
  745. # 是否已存在
  746. if email_qs.exists():
  747. return response.json(103)
  748. try:
  749. users = Device_User.objects.create(
  750. userEmail=email,
  751. password=password,
  752. userID=CommonService.getUserID(μs=False, setOTAID=True),
  753. is_active=True,
  754. user_isValid=True,
  755. )
  756. except Exception as e:
  757. errorInfo = traceback.format_exc()
  758. print(errorInfo)
  759. return response.json(424, repr(e))
  760. else:
  761. if not reds.del_data(key=email + '_identifyingCode'):
  762. return response.json(10, '删除缓存验证码错误')
  763. return self.do_login(email_qs, response)
  764. # 忘记密码获取验证码v2
  765. class v2forgetPwdCodeView(TemplateView):
  766. @method_decorator(csrf_exempt)
  767. def dispatch(self, *args, **kwargs):
  768. return super(v2forgetPwdCodeView, self).dispatch(*args, **kwargs)
  769. @ratelimit(key='ip', rate='1/m')
  770. def get(self, request, *args, **kwargs):
  771. request.encoding = 'utf-8'
  772. request_dict = request.GET
  773. lang = request_dict.get('lang')
  774. response = ResponseObject(lang)
  775. was_limited = getattr(request, 'limited', False)
  776. if was_limited is True:
  777. return response.json(5)
  778. return self.ValidationError(request_dict, response)
  779. @ratelimit(key='ip', rate='1/m')
  780. def post(self, request):
  781. request.encoding = 'utf-8'
  782. request_dict = request.POST
  783. lang = request_dict.get('lang')
  784. response = ResponseObject(lang)
  785. was_limited = getattr(request, 'limited', False)
  786. if was_limited is True:
  787. return response.json(5)
  788. return self.ValidationError(request_dict, response)
  789. def ValidationError(self, request_dict, response):
  790. phone = request_dict.get('phone', None)
  791. # email = request_dict.get('email', None)
  792. if phone is not None:
  793. phone = phone.strip()
  794. return self.do_phone_pwd_forget(phone, response)
  795. else:
  796. return response.json(444, 'phone')
  797. def do_phone_pwd_forget(self, phone, response):
  798. data_valid = DataValid()
  799. if data_valid.mobile_validate(phone) is not True:
  800. return response.json(100)
  801. user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
  802. if not user_qs.exists():
  803. return response.json(102)
  804. reds = RedisObject()
  805. resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
  806. if resetCode is True:
  807. return response.json(90)
  808. resetCode = RandomStr(6, True)
  809. if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
  810. return response.json(10, '生成缓存错误')
  811. aliSms = AliSmsObject()
  812. res = aliSms.send_code_sms(phone=phone, code=resetCode, sign_name='Ansjer',
  813. temp_msg='SMS_151675019')
  814. if res["Code"] == "OK":
  815. return response.json(0, {'forgetPwdResetCode': resetCode})
  816. else:
  817. return response.json(10, res["Message"])
  818. # 忘记密码v2
  819. class v2resetPwdByCodeView(TemplateView):
  820. @method_decorator(csrf_exempt)
  821. def dispatch(self, *args, **kwargs):
  822. return super(v2resetPwdByCodeView, self).dispatch(*args, **kwargs)
  823. def get(self, request, *args, **kwargs):
  824. request.encoding = 'utf-8'
  825. request_dict = request.GET
  826. lang = request_dict.get('lang')
  827. response = ResponseObject(lang)
  828. was_limited = getattr(request, 'limited', False)
  829. if was_limited is True:
  830. return response.json(5)
  831. return self.ValidationError(request_dict, response)
  832. def post(self, request):
  833. request.encoding = 'utf-8'
  834. request_dict = request.POST
  835. lang = request_dict.get('lang')
  836. response = ResponseObject(lang)
  837. was_limited = getattr(request, 'limited', False)
  838. if was_limited is True:
  839. return response.json(5)
  840. return self.ValidationError(request_dict, response)
  841. def ValidationError(self, request_dict, response):
  842. phone = request_dict.get('phone', None)
  843. password = request_dict.get('password', None)
  844. authcode = request_dict.get('authcode', None)
  845. if phone is not None and password is not None and authcode is not None:
  846. phone = phone.strip()
  847. authcode = authcode.strip()
  848. password = password.strip()
  849. return self.do_phone_pwd_reset(phone, authcode, password, response)
  850. else:
  851. return response.json(444, 'phone,password,authcode')
  852. def do_phone_pwd_reset(self, phone, authcode, password, response):
  853. data_valid = DataValid()
  854. if data_valid.mobile_validate(phone) is not True:
  855. return response.json(100)
  856. if data_valid.password_validate(password) is not True:
  857. return response.json(109)
  858. user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
  859. if not user_qs.exists():
  860. return response.json(102)
  861. reds = RedisObject()
  862. resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
  863. if resetCode is True:
  864. return response.json(90)
  865. if authcode != resetCode:
  866. return response.json(121)
  867. if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
  868. return response.json(10, '生成缓存错误')
  869. user_qs.update(password=make_password(password))
  870. if not reds.del_data(phone + '_forgetPwdResetCode'):
  871. return response.json(10, '删除缓存失败')
  872. return response.json(0)
  873. # 登录
  874. class v2LoginView(TemplateView):
  875. @method_decorator(csrf_exempt) # @csrf_exempt
  876. def dispatch(self, *args, **kwargs):
  877. return super(v2LoginView, self).dispatch(*args, **kwargs)
  878. @ratelimit(key='ip', rate='5/m')
  879. def post(self, request, *args, **kwargs):
  880. request.encoding = 'utf-8'
  881. request_dict = request.POST
  882. language = request_dict.get('language', 'en')
  883. response = ResponseObject(language)
  884. was_limited = getattr(request, 'limited', False)
  885. if was_limited is True:
  886. return response.json(5)
  887. return self.validates(request_dict, response)
  888. @ratelimit(key='ip', rate='5/m')
  889. def get(self, request, *args, **kwargs):
  890. request.encoding = 'utf-8'
  891. request_dict = request.GET
  892. language = request_dict.get('language', 'en')
  893. response = ResponseObject(language)
  894. was_limited = getattr(request, 'limited', False)
  895. if was_limited is True:
  896. return response.json(5)
  897. return self.validates(request_dict, response)
  898. def validates(self, request_dict, response):
  899. username = request_dict.get('userName', None)
  900. password = request_dict.get('userPwd', None)
  901. # mcode = request_dict.get('mobileMechanicalCode', '')
  902. if username is not None and password is not None:
  903. username = username.strip()
  904. password = password.strip()
  905. data_valid = DataValid()
  906. if data_valid.email_validate(username):
  907. return self.do_email_login(username, password, response)
  908. elif data_valid.mobile_validate(username):
  909. return self.do_phone_login(username, password, response)
  910. elif data_valid.name_validate(username):
  911. return self.do_name_login(username, password, response)
  912. else:
  913. return response.json(107)
  914. else:
  915. return response.json(111)
  916. return response.json(444, 'username,password')
  917. def do_email_login(self, email, password, response):
  918. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  919. if not user_qs.exists():
  920. return response.json(104)
  921. if not user_qs[0].user_isValid or not user_qs[0].is_active:
  922. return response.json(110)
  923. return self.valid_login(user_qs, password, response)
  924. def do_phone_login(self, phone, password, response):
  925. user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
  926. if not user_qs.exists():
  927. return response.json(104)
  928. if not user_qs[0].user_isValid or not user_qs[0].is_active:
  929. return response.json(110)
  930. return self.valid_login(user_qs, password, response)
  931. def do_name_login(self, username, password, response):
  932. user_qs = Device_User.objects.filter(username=username)
  933. if not user_qs.exists():
  934. return response.json(104)
  935. if not user_qs[0].user_isValid or not user_qs[0].is_active:
  936. return response.json(110)
  937. return self.valid_login(user_qs, password, response)
  938. def valid_login(self, user_qs, password, response):
  939. if not check_password(password, user_qs[0].password):
  940. return response.json(111)
  941. userID = user_qs[0].userID
  942. print('userID' + userID)
  943. tko = TokenObject()
  944. res = tko.generate(data={'userID': userID, 'lang': response.lang})
  945. if tko.code == 0:
  946. now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
  947. user_qs.update(last_login=now_time, online=True, language=response.lang)
  948. role_dict = ModelService.own_role(userID=userID)
  949. res['rid'] = role_dict['rid']
  950. res['roleName'] = role_dict['roleName']
  951. res['permList'] = ModelService.own_permission(userID)
  952. res['userID'] = userID
  953. print(res)
  954. return response.json(0, res)
  955. else:
  956. return response.json(tko.code)