1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
- @AUTHOR: ASJRD018
- @NAME: AnsjerFormal
- @software: PyCharm
- @DATE: 2018/9/11 15:08
- @Version: python3.6
- @MODIFY DECORD:ansjer dev
- @file: UserController.py
- @Contact: chanjunkai@163.com
- """
- import traceback,datetime
- import simplejson as json
- from django.contrib import auth
- from django.contrib.auth.hashers import make_password, check_password # 对密码加密模块
- from django.http import HttpResponseRedirect
- from django.utils.decorators import method_decorator
- from django.utils.timezone import utc
- from django.views.decorators.csrf import csrf_exempt
- from django.views.generic import TemplateView
- from ratelimit.decorators import ratelimit
- from Controller.CheckUserData import DataValid, date_handler, RandomStr
- from Model.models import Device_User
- from Object.AWS.SesClassObject import SesClassObject
- from Object.RedisObject import RedisObject
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Service.CommonService import CommonService
- from Service.MiscellService import MiscellService
- from Service.ModelService import ModelService
- from Service.TemplateService import TemplateService
- from Object.AliSmsObject import AliSmsObject
- from django.db.models import Q
- from Ansjer.config import AuthCode_Expire,SERVER_DOMAIN
- # 获取验证码
- class authCodeView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(authCodeView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='2/m')
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- lang = request.POST.get('language', None)
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- username = request.POST.get('userName', None)
- useremail = request.POST.get('userEmail', None)
- return self.ValidationError(username, useremail, response)
- # @ratelimit(key='ip', rate='2/m')
- def get(self, request, *args, **kwargs):
- # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
- request.encoding = 'utf-8'
- lang = request.GET.get('language', None)
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- username = request.GET.get('userName', None)
- email = request.GET.get('userEmail', None)
- return self.ValidationError(username, email, response)
- def ValidationError(self, username, email, response):
- if username:
- username = username.strip()
- return self.phoneCode(username, response)
- elif email:
- email = email.strip()
- return self.emailCode(email, response)
- else:
- return response.json(800)
- def phoneCode(self, phone, response):
- dataValid = DataValid()
- if dataValid.mobile_validate(phone):
- reds = RedisObject()
- identifyingCode = reds.get_data(key=phone + '_identifyingCode')
- if identifyingCode is False:
- user_qs = Device_User.objects.filter(username=phone)
- if user_qs.exists():
- return response.json(101)
- else:
- identifyingCode = RandomStr(6, True)
- if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=600):
- return response.json(0, {'identifyingCode': identifyingCode})
- else:
- return response.json(10, '生成缓存系统错误')
- else:
- return response.json(0, {'identifyingCode': identifyingCode})
- else:
- return response.json(107)
- def emailCode(self, email, response):
- dataValid = DataValid()
- if dataValid.email_validate(email):
- reds = RedisObject()
- identifyingCode = reds.get_data(key=email + '_identifyingCode')
- if identifyingCode is False:
- user_qs = Device_User.objects.filter(username=email)
- email_qs = Device_User.objects.filter(userEmail=email)
- if user_qs.exists():
- return response.json(103)
- elif email_qs.exists():
- return response.json(103)
- else:
- identifyingCode = RandomStr(6, True)
- if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire):
- send_data = TemplateService.email_message(type='register_code', language=response.lang)
- ses = SesClassObject()
- send_res = ses.send_email(
- send_address_list=[email],
- subject=send_data['title'],
- body=send_data['body'].replace("{username}", email).replace("{captcha}",
- str(identifyingCode))
- )
- if send_res:
- reds.set_data(key=email + '_registerCode', val=identifyingCode, expire=AuthCode_Expire)
- return response.json(0, {'identifyingCode': identifyingCode})
- else:
- return response.json(44)
- else:
- return response.json(10, '生成缓存系统错误')
- else:
- return response.json(89, {'identifyingCode': identifyingCode})
- else:
- return response.json(107)
- # 验证码注册
- class registerView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(registerView, self).dispatch(*args, **kwargs)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.POST
- return self.validates(request_dict)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- return self.validates(request_dict)
- def validates(self, request_dict):
- username = request_dict.get('userName', None)
- userEmail = request_dict.get('userEmail', None)
- password = request_dict.get('userPwd', None)
- authCode = request_dict.get('identifyingCode', None)
- language = request_dict.get('language', None)
- response = ResponseObject(language)
- if username and password and authCode:
- # 过滤空格
- username = username.strip()
- if userEmail:
- userEmail = userEmail.strip()
- return self.register(username, userEmail, password, authCode, response)
- else:
- return response.json(800)
- def register(self, username, userEmail, password, authCode, response):
- dataValid = DataValid()
- reds = RedisObject()
- identifyingCode = reds.get_data(key=username + '_identifyingCode')
- if identifyingCode is False:
- if userEmail:
- identifyingCode = reds.get_data(key=userEmail + '_identifyingCode')
- if identifyingCode is False:
- return response.json(120)
- else:
- username = userEmail
- else:
- return response.json(120)
- if authCode != identifyingCode:
- return response.json(121)
- if dataValid.password_validate(password):
- if dataValid.email_validate(username):
- if userEmail:
- print(userEmail)
- emailValid = Device_User.objects.filter(userEmail=userEmail)
- if emailValid.exists():
- return response.json(103)
- else:
- userEmail = username
- if username:
- nameValid = Device_User.objects.filter(username=username)
- if nameValid.exists():
- return response.json(101)
- try:
- create_data = {
- "username": username,
- "userEmail": userEmail,
- "password": make_password(password),
- "userID": CommonService.getUserID(μs=False, setOTAID=True),
- "is_active": True,
- "user_isValid": True,
- }
- users = Device_User.objects.create(**create_data)
- except Exception as e:
- errorInfo = traceback.format_exc()
- print(errorInfo)
- return response.json(424, repr(e))
- else:
- if reds.del_data(key=username + '_identifyingCode'):
- return response.json(0, {
- "user": {
- "userID": users.userID,
- "username": users.username,
- "userEmail": users.userEmail,
- "NickName": users.NickName,
- "userIconUrl": str(users.userIconUrl),
- "is_superuser": users.is_superuser,
- "is_active": users.is_active,
- "data_joined": date_handler(users.data_joined),
- "last_login": date_handler(users.last_login),
- }
- })
- else:
- return response.json(10, '删除缓存验证码错误')
- elif dataValid.mobile_validate(username):
- nameValid = Device_User.objects.filter(username=username)
- if nameValid:
- return response.json(101)
- try:
- create_data = {
- "username": username,
- "userEmail": userEmail,
- "password": make_password(password),
- "userID": CommonService.getUserID(μs=False, setOTAID=True),
- "is_active": True,
- "user_isValid": True,
- }
- users = Device_User.objects.create(**create_data)
- except Exception as e:
- errorInfo = traceback.format_exc()
- print(errorInfo)
- return response.json(424, repr(e))
- else:
- if reds.del_data(key=username + '_identifyingCode'):
- return response.json(0, {
- "user": {
- "userID": users.userID,
- "username": users.username,
- "userEmail": users.userEmail,
- "NickName": users.NickName,
- "userIconUrl": str(users.userIconUrl),
- "is_superuser": users.is_superuser,
- "is_active": users.is_active,
- "data_joined": date_handler(users.data_joined),
- "last_login": date_handler(users.last_login),
- }
- })
- else:
- return response.json(10, '删除缓存验证码错误')
- else:
- return response.json(107)
- else:
- return response.json(109)
- # 登录
- class LoginView(TemplateView):
- @method_decorator(csrf_exempt) # @csrf_exempt
- def dispatch(self, *args, **kwargs):
- return super(LoginView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='5/m')
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.POST
- language = request_dict.get('language', 'en')
- response = ResponseObject(language)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.validates(request_dict, response)
- @ratelimit(key='ip', rate='5/m')
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- language = request_dict.get('language', 'en')
- response = ResponseObject(language)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.validates(request_dict, response)
- def validates(self, request_dict, response):
- username = request_dict.get('userName', None)
- password = request_dict.get('userPwd', None)
- print(username)
- print(password)
- mcode = request_dict.get('mobileMechanicalCode', '')
- if username and password:
- username = username.strip()
- password = password.strip()
- return self.login(username, password, mcode, response)
- else:
- return response.json(444, 'username,password')
- def login(self, username, password, mcode, response):
- dataValid = DataValid()
- if dataValid.mobile_validate(username):
- userValid = Device_User.objects.filter(username=username)
- if userValid:
- if userValid[0].user_isValid and userValid[0].is_active:
- c_p = check_password(password, userValid[0].password)
- if c_p:
- return self.LoginUpdate(userValid, mcode, response)
- else:
- return response.json(111)
- else:
- return response.json(110)
- else:
- return response.json(102)
- elif dataValid.email_validate(username):
- userValid = Device_User.objects.filter(userEmail=username)
- if userValid:
- if userValid[0].user_isValid and userValid[0].is_active:
- User = auth.authenticate(username=userValid[0].username, password=password)
- if User is not None:
- return self.LoginUpdate(userValid, mcode, response)
- else:
- return response.json(111)
- else:
- return response.json(110)
- else:
- return response.json(104)
- else:
- return response.json(104)
- def LoginUpdate(self, userValid, mcode, response):
- userID = userValid[0].userID
- print('userID' + userID)
- tko = TokenObject()
- res = tko.generate(data={'userID': userID, 'lang': response.lang, 'mcode': mcode})
- if tko.code == 0:
- now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
- userValid.update(last_login=now_time, online=True, machine_code=mcode, language=response.lang)
- role_dict = ModelService.own_role(userID=userID)
- res['rid'] = role_dict['rid']
- res['roleName'] = role_dict['roleName']
- res['permList'] = ModelService.own_permission(userID)
- res['userID'] = userID
- print(res)
- return response.json(0, res)
- else:
- return response.json(tko.code)
- # 登出
- class LogoutView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(LogoutView, self).dispatch(*args, **kwargs)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- token = request.POST.get('token')
- return self.Logout(request, token)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- token = request.GET.get('token')
- return self.Logout(request, token)
- def Logout(self, request, token):
- response = ResponseObject()
- if token:
- tko = TokenObject(token)
- tko.valid()
- if tko.code == 0:
- try:
- MiscellService.add_access_log(request=request, status_code=200)
- except Exception as e:
- pass
- is_udpate = Device_User.objects.filter(userID=tko.userID).update(online=False)
- if is_udpate:
- return response.json(0)
- else:
- return response.json(tko.code)
- else:
- return response.json(800)
- # 修改密码
- class ChangePwdView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(ChangePwdView, self).dispatch(*args, **kwargs)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.POST
- return self.validates(request_dict)
- def get(self, request, *args, **kwargs):
- request.encoding = 'gb2312'
- request_dict = request.GET
- return self.validates(request_dict)
- def validates(self, request_dict):
- token = request_dict.get('token', None)
- oldPwd = request_dict.get('oldPwd', None)
- newPwd = request_dict.get('newPwd', None)
- response = ResponseObject()
- if token and oldPwd and newPwd:
- tko = TokenObject(token)
- tko.valid()
- response.lang = tko.lang
- if tko.code == 0:
- return self.updatePwd(tko.userID, oldPwd, newPwd, response)
- else:
- return response.json(tko.code)
- else:
- return response.json(800)
- def updatePwd(self, userID, oldPwd, newPwd, response):
- user_qs = Device_User.objects.filter(userID=userID)
- if user_qs.exists():
- c_p = check_password(oldPwd, user_qs[0].password)
- if c_p:
- update = user_qs.update(password=make_password(newPwd))
- if update:
- return response.json(0)
- else:
- return response.json(112)
- else:
- return response.json(111)
- else:
- return response.json(113)
- class ForgetPwdView(TemplateView):
- '''
- 忘记密码
- '''
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(ForgetPwdView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='1/m')
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- response = ResponseObject()
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- userName = request.GET.get('userName', None)
- return self.ValidationError(userName, response)
- @ratelimit(key='ip', rate='1/m')
- def post(self, request):
- request.encoding = 'utf-8'
- userName = request.POST.get('userName', None)
- response = ResponseObject()
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.ValidationError(userName, response)
- def ValidationError(self, userName, response):
- if userName != None:
- userName = userName.strip()
- return self.ForgetPwd(userName, response)
- else:
- return response.json(800)
- def ForgetPwd(self, userName, response):
- dataValid = DataValid()
- if dataValid.mobile_validate(userName):
- User = Device_User.objects.filter(username=userName)
- elif dataValid.email_validate(userName):
- User = Device_User.objects.filter(username=userName)
- if not User.exists():
- User = Device_User.objects.filter(userEmail=userName)
- else:
- return response.json(9)
- if User:
- email = User[0].userEmail
- userID = User[0].userID
- if email:
- redisObj = RedisObject()
- reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
- if reset_pwd is False:
- tko = TokenObject()
- rest = tko.generate(data={'userID': userID})
- token = rest['access_token']
- reset_pwd = CommonService.RandomStr(6)
- send_data = TemplateService.email_message(type='forget', language='en')
- reset_link = '{server_host}/account/email-re-pwd?token={token}'.format(
- server_host=SERVER_DOMAIN, token=token)
- send_body = send_data['body'].format(username=email, reset_pwd=reset_pwd, reset_link=reset_link)
- ses = SesClassObject()
- send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
- if send_res is True:
- if redisObj.set_data(key=userID + '_email_reset_pwd', val=reset_pwd, expire=3600):
- return response.json(0)
- else:
- return response.json(10, '存储验证失败')
- else:
- return response.json(89)
- else:
- return response.json(103)
- else:
- return response.json(9)
- class EmailResetPwdView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(EmailResetPwdView, self).dispatch(*args, **kwargs)
- # 查询
- def get(self, request, *args, **kwargs):
- response = ResponseObject()
- request_dict = request.GET
- return self.validate(request_dict, response, *args, **kwargs)
- # 认证登录
- def post(self, request, *args, **kwargs):
- response = ResponseObject()
- try:
- print(request.body.decode("utf-8"))
- json_data = json.loads(request.body.decode("utf-8"))
- except Exception as e:
- return response.json(10, repr(e))
- else:
- request_dict = json_data
- return self.validate(request_dict, response, *args, **kwargs)
- def validate(self, request_dict, response, *args, **kwargs):
- token = request_dict.get('token', None)
- if token is not None:
- tko = TokenObject(token)
- tko.valid()
- if tko.code == 0:
- redisObj = RedisObject()
- userID = tko.userID
- reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
- if reset_pwd is not False:
- user_qs = Device_User.objects.filter(userID=userID)
- if user_qs.exists():
- redisObj.del_data(key=userID + '_email_reset_pwd')
- is_update = user_qs.update(password=make_password(reset_pwd))
- if is_update:
- return HttpResponseRedirect(
- "http://www.dvema.com/web/html/paw_update_success.html?code=" + reset_pwd)
- else:
- return response.json(10)
- else:
- return response.json(9)
- else:
- return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
- return response.json(306, 'rpwd')
- else:
- return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
- return response.json(tko.code)
- else:
- return response.json(444, 'token')
- class refreshTokenView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(refreshTokenView, self).dispatch(*args, **kwargs)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = json.loads(request.body.decode('utf-8'))
- return self.validation(request_dict)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- return self.validation(request_dict)
- def validation(self, request_dict):
- token = request_dict.get('token', None)
- lang = request_dict.get('lang', None)
- response = ResponseObject(lang)
- if token is not None:
- tko = TokenObject(token)
- res = tko.refresh()
- code = tko.code
- if code == 0:
- return response.json(0, res)
- else:
- return response.json(code)
- else:
- return response.json(444, 'token')
- # 获取验证码
- class v2authCodeView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(v2authCodeView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='2/m')
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- lang = request.POST.get('lang', None)
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- request_dict = request.POST
- return self.ValidationError(request_dict, response)
- @ratelimit(key='ip', rate='2/m')
- def get(self, request, *args, **kwargs):
- # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
- request.encoding = 'utf-8'
- lang = request.GET.get('lang', None)
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- request_dict = request.GET
- return self.ValidationError(request_dict, response)
- def ValidationError(self, request_dict, response):
- email = request_dict.get('email', None)
- phone = request_dict.get('phone', None)
- if email is not None:
- email = email.strip()
- return self.emailCode(email, response)
- elif phone is not None:
- phone = phone.strip()
- return self.phoneCode(phone, response)
- else:
- return response.json(444)
- def emailCode(self, email, response):
- dataValid = DataValid()
- # 邮箱匹配
- if dataValid.email_validate(email) is False:
- return response.json(107)
- reds = RedisObject()
- identifyingCode = reds.get_data(key=email + '_identifyingCode')
- # 是否以获取邮箱验证码
- if identifyingCode is True:
- return response.json(89)
- user_qs = Device_User.objects.filter(username=email)
- email_qs = Device_User.objects.filter(userEmail=email)
- # 邮箱用户是否已存在
- if user_qs.exists():
- return response.json(103)
- elif email_qs.exists():
- return response.json(103)
- # 生成随机6位数
- identifyingCode = RandomStr(6, True)
- # 设置随机数缓存生命周期
- if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire) is not True:
- return response.json(10, '生成缓存系统错误')
- send_data = TemplateService.email_message(type='register_code', language=response.lang)
- ses = SesClassObject()
- # 发送邮件
- send_res = ses.send_email(
- send_address_list=[email],
- subject=send_data['title'],
- body=send_data['body'].replace("{username}", email).replace("{captcha}",
- str(identifyingCode))
- )
- if send_res is not True:
- return response.json(44)
- reds.set_data(key=email + '_registerCode', val=identifyingCode, expire=AuthCode_Expire)
- return response.json(0, {'identifyingCode': identifyingCode})
- def phoneCode(self, phone, response):
- dataValid = DataValid()
- if dataValid.mobile_validate(phone) is not True:
- return response.json(107)
- reds = RedisObject()
- identifyingCode = reds.get_data(key=phone + '_identifyingCode')
- if identifyingCode:
- return response.json(90)
- user_qs = Device_User.objects.filter(username=phone)
- phone_qs = Device_User.objects.filter(phone=phone)
- if user_qs.exists() or phone_qs.exists():
- return response.json(101)
- identifyingCode = RandomStr(6, True)
- if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=300) is not True:
- return response.json(10, '生成缓存系统错误')
- # 发送手机验证码
- aliSms = AliSmsObject()
- res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name='Ansjer',
- temp_msg='SMS_151600991')
- if res["Code"] == "OK":
- return response.json(0)
- # return response.json(0, {'identifyingCode': identifyingCode})
- else:
- return response.json(10, res["Message"])
- # 验证码注册
- class v2registerView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(v2registerView, self).dispatch(*args, **kwargs)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.POST
- return self.validates(request_dict)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- return self.validates(request_dict)
- def validates(self, request_dict):
- phone = request_dict.get('phone', None)
- email = request_dict.get('email', None)
- password = request_dict.get('password', None)
- authcode = request_dict.get('authcode', None)
- lang = request_dict.get('lang', None)
- response = ResponseObject(lang)
- if password is None:
- return response.json(444, 'password')
- if authcode is None:
- return response.json(444, 'identifyingCode')
- if phone is not None:
- return self.do_phone_register(phone, password, authcode, response)
- elif email is not None:
- return self.do_email_register(email, password, authcode, response)
- else:
- return response.json(444, 'phone or email')
- def do_phone_register(self, phone, password, authcode, response):
- data_valid = DataValid()
- if data_valid.mobile_validate(phone) is not True:
- return response.json(100)
- if data_valid.password_validate(password) is not True:
- return response.json(109)
- reds = RedisObject()
- identifyingCode = reds.get_data(key=phone + '_identifyingCode')
- # 判断验证码是否过期
- if identifyingCode is False:
- return response.json(120)
- # 验证码是否正确
- if authcode != identifyingCode:
- return response.json(121)
- phone_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
- # 是否已存在
- if phone_qs.exists():
- return response.json(101)
- try:
- users = Device_User.objects.create(
- phone=phone,
- password=password,
- userID=CommonService.getUserID(μs=False, setOTAID=True),
- is_active=True,
- user_isValid=True,
- )
- except Exception as e:
- errorInfo = traceback.format_exc()
- print(errorInfo)
- return response.json(424, repr(e))
- else:
- if not reds.del_data(key=phone + '_identifyingCode'):
- return response.json(10, '删除缓存验证码错误')
- return self.do_login(phone_qs, response)
- def do_login(self, user_qs, response):
- userID = user_qs[0].userID
- print('userID' + userID)
- tko = TokenObject()
- res = tko.generate(data={'userID': userID, 'lang': response.lang})
- if tko.code == 0:
- now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
- user_qs.update(last_login=now_time, online=True, language=response.lang)
- role_dict = ModelService.own_role(userID=userID)
- res['rid'] = role_dict['rid']
- res['roleName'] = role_dict['roleName']
- res['permList'] = ModelService.own_permission(userID)
- res['userID'] = userID
- print(res)
- return response.json(0, res)
- else:
- return response.json(tko.code)
- def do_email_register(self, email, password, authcode, response):
- data_valid = DataValid()
- if data_valid.email_validate(email) is not True:
- return response.json(105)
- if data_valid.password_validate(password) is not True:
- return response.json(109)
- reds = RedisObject()
- identifyingCode = reds.get_data(key=email + '_identifyingCode')
- # 判断验证码是否过期
- if identifyingCode is False:
- return response.json(120)
- # 验证码是否正确
- if authcode != identifyingCode:
- return response.json(121)
- email_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
- # 是否已存在
- if email_qs.exists():
- return response.json(103)
- try:
- users = Device_User.objects.create(
- userEmail=email,
- password=password,
- userID=CommonService.getUserID(μs=False, setOTAID=True),
- is_active=True,
- user_isValid=True,
- )
- except Exception as e:
- errorInfo = traceback.format_exc()
- print(errorInfo)
- return response.json(424, repr(e))
- else:
- if not reds.del_data(key=email + '_identifyingCode'):
- return response.json(10, '删除缓存验证码错误')
- return self.do_login(email_qs, response)
- # 忘记密码获取验证码v2
- class v2forgetPwdCodeView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(v2forgetPwdCodeView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='1/m')
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- lang = request_dict.get('lang')
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.ValidationError(request_dict, response)
- @ratelimit(key='ip', rate='1/m')
- def post(self, request):
- request.encoding = 'utf-8'
- request_dict = request.POST
- lang = request_dict.get('lang')
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.ValidationError(request_dict, response)
- def ValidationError(self, request_dict, response):
- phone = request_dict.get('phone', None)
- # email = request_dict.get('email', None)
- if phone is not None:
- phone = phone.strip()
- return self.do_phone_pwd_forget(phone, response)
- else:
- return response.json(444, 'phone')
- def do_phone_pwd_forget(self, phone, response):
- data_valid = DataValid()
- if data_valid.mobile_validate(phone) is not True:
- return response.json(100)
- user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
- if not user_qs.exists():
- return response.json(102)
- reds = RedisObject()
- resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
- if resetCode is True:
- return response.json(90)
- resetCode = RandomStr(6, True)
- if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
- return response.json(10, '生成缓存错误')
- aliSms = AliSmsObject()
- res = aliSms.send_code_sms(phone=phone, code=resetCode, sign_name='Ansjer',
- temp_msg='SMS_151675019')
- if res["Code"] == "OK":
- return response.json(0, {'forgetPwdResetCode': resetCode})
- else:
- return response.json(10, res["Message"])
- # 忘记密码v2
- class v2resetPwdByCodeView(TemplateView):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(v2resetPwdByCodeView, self).dispatch(*args, **kwargs)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- lang = request_dict.get('lang')
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.ValidationError(request_dict, response)
- def post(self, request):
- request.encoding = 'utf-8'
- request_dict = request.POST
- lang = request_dict.get('lang')
- response = ResponseObject(lang)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.ValidationError(request_dict, response)
- def ValidationError(self, request_dict, response):
- phone = request_dict.get('phone', None)
- password = request_dict.get('password', None)
- authcode = request_dict.get('authcode', None)
- if phone is not None and password is not None and authcode is not None:
- phone = phone.strip()
- authcode = authcode.strip()
- password = password.strip()
- return self.do_phone_pwd_reset(phone, authcode, password, response)
- else:
- return response.json(444, 'phone,password,authcode')
- def do_phone_pwd_reset(self, phone, authcode, password, response):
- data_valid = DataValid()
- if data_valid.mobile_validate(phone) is not True:
- return response.json(100)
- if data_valid.password_validate(password) is not True:
- return response.json(109)
- user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
- if not user_qs.exists():
- return response.json(102)
- reds = RedisObject()
- resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
- if resetCode is True:
- return response.json(90)
- if authcode != resetCode:
- return response.json(121)
- if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
- return response.json(10, '生成缓存错误')
- user_qs.update(password=make_password(password))
- if not reds.del_data(phone + '_forgetPwdResetCode'):
- return response.json(10, '删除缓存失败')
- return response.json(0)
- # 登录
- class v2LoginView(TemplateView):
- @method_decorator(csrf_exempt) # @csrf_exempt
- def dispatch(self, *args, **kwargs):
- return super(v2LoginView, self).dispatch(*args, **kwargs)
- @ratelimit(key='ip', rate='5/m')
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.POST
- language = request_dict.get('language', 'en')
- response = ResponseObject(language)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.validates(request_dict, response)
- @ratelimit(key='ip', rate='5/m')
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- request_dict = request.GET
- language = request_dict.get('language', 'en')
- response = ResponseObject(language)
- was_limited = getattr(request, 'limited', False)
- if was_limited is True:
- return response.json(5)
- return self.validates(request_dict, response)
- def validates(self, request_dict, response):
- username = request_dict.get('userName', None)
- password = request_dict.get('userPwd', None)
- # mcode = request_dict.get('mobileMechanicalCode', '')
- if username is not None and password is not None:
- username = username.strip()
- password = password.strip()
- data_valid = DataValid()
- if data_valid.email_validate(username):
- return self.do_email_login(username, password, response)
- elif data_valid.mobile_validate(username):
- return self.do_phone_login(username, password, response)
- elif data_valid.name_validate(username):
- return self.do_name_login(username, password, response)
- else:
- return response.json(107)
- else:
- return response.json(111)
- return response.json(444, 'username,password')
- def do_email_login(self, email, password, response):
- user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
- if not user_qs.exists():
- return response.json(104)
- if not user_qs[0].user_isValid or not user_qs[0].is_active:
- return response.json(110)
- return self.valid_login(user_qs, password, response)
- def do_phone_login(self, phone, password, response):
- user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
- if not user_qs.exists():
- return response.json(104)
- if not user_qs[0].user_isValid or not user_qs[0].is_active:
- return response.json(110)
- return self.valid_login(user_qs, password, response)
- def do_name_login(self, username, password, response):
- user_qs = Device_User.objects.filter(username=username)
- if not user_qs.exists():
- return response.json(104)
- if not user_qs[0].user_isValid or not user_qs[0].is_active:
- return response.json(110)
- return self.valid_login(user_qs, password, response)
- def valid_login(self, user_qs, password, response):
- if not check_password(password, user_qs[0].password):
- return response.json(111)
- userID = user_qs[0].userID
- print('userID' + userID)
- tko = TokenObject()
- res = tko.generate(data={'userID': userID, 'lang': response.lang})
- if tko.code == 0:
- now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
- user_qs.update(last_login=now_time, online=True, language=response.lang)
- role_dict = ModelService.own_role(userID=userID)
- res['rid'] = role_dict['rid']
- res['roleName'] = role_dict['roleName']
- res['permList'] = ModelService.own_permission(userID)
- res['userID'] = userID
- print(res)
- return response.json(0, res)
- else:
- return response.json(tko.code)
|