Эх сурвалжийг харах

Merge remote-tracking branch 'remotes/origin/dev' into test

tanghongbin 4 жил өмнө
parent
commit
e726a371c2

+ 2 - 0
Ansjer/urls.py

@@ -233,6 +233,8 @@ urlpatterns = [
     url(r'^ios/authsign', UserController.AppleAuthLogin.as_view()),
     url(r'^appLog/(?P<operation>.*)$', AppLogController.AppLogView.as_view()),
 
+    # 本地登录接口
+    url(r'^local/(?P<operation>.*)$', UserController.LocalUserView.as_view()),
 
     # app 设备消息模板
     # 路由加参数参考

+ 128 - 1
Controller/UserController.py

@@ -173,6 +173,9 @@ class registerView(TemplateView):
         password = request_dict.get('userPwd', None)
         authCode = request_dict.get('identifyingCode', None)
         language = request_dict.get('language', None)
+        unique = request_dict.get('unique', None)
+        if unique:
+            delete_local_account(unique)
         response = ResponseObject(language)
         if username and password and authCode:
             # 过滤空格
@@ -286,7 +289,6 @@ class registerView(TemplateView):
         else:
             return response.json(109)
 
-
 # 登出
 class LogoutView(TemplateView):
     @method_decorator(csrf_exempt)
@@ -858,6 +860,9 @@ class v2registerView(TemplateView):
         password = request_dict.get('password', None)
         authcode = request_dict.get('authcode', None)
         lang = request_dict.get('lang', None)
+        unique = request_dict.get('unique', None)
+        if unique:
+            delete_local_account(unique)
         response = ResponseObject(lang)
         if not lang:
             lang = request_dict.get('language', None)
@@ -998,6 +1003,9 @@ class v3registerView(TemplateView):
         password = request_dict.get('password', None)
         authcode = request_dict.get('authcode', None)
         lang = request_dict.get('lang', None)
+        unique = request_dict.get('unique', None)
+        if unique:
+            delete_local_account(unique)
         response = ResponseObject(lang)
         # 解密
         try:
@@ -1150,6 +1158,14 @@ class v3registerView(TemplateView):
                 return response.json(10, '删除缓存验证码错误')
             return self.do_login(email_qs, response)
 
+    def delete_local_account(self, username):
+        user_qs = Device_User.objects.filter(username=username)
+        if user_qs.exists():
+            user: Device_User = user_qs[0]
+            if user.is_local:
+                user.delete()
+                Device_Info.objects.filter(userID__userID=user.userID).delete()
+
 
 # 重置密码
 # 忘记密码获取验证码v2
@@ -2847,6 +2863,9 @@ class Image_Code_RegisterView(TemplateView):
         # 页面输入的验证码
         response = ResponseObject(lang)
         valid_code = request_dict.get('id_v_code', None)
+        unique = request_dict.get('unique', None)
+        if unique:
+            delete_local_account(unique)
 
         if not all([userEmail, password, lang, imageCodeId, valid_code]):
             return response.json(444)
@@ -3455,3 +3474,111 @@ class AppleAuthLogin(View):
             print('---')
             print(user_qs)
             return self.do_login(user_qs, response)
+
+
+class LocalUserView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation, CommonService.get_ip_address(request))
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation, CommonService.get_ip_address(request))
+
+    def validate(self, request_dict, operation, ip):
+        language = request_dict.get('language', None)
+        response = ResponseObject(lang=language)
+        print(CommonService.getAddr(ip))
+        if operation == 'login':
+            return self.do_local_login(request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_local_login(self, request_dict, response):
+        username = request_dict.get('username', None)
+        app_bundle_id = request_dict.get('app_bundle_id', None)
+
+        user_qs = Device_User.objects.filter(username=username)
+        if user_qs.exists():
+            return self.do_login(user_qs, response)
+        else:
+            # 如果用户为绑定过则创建用户并进行登录返回token
+            userID = CommonService.getUserID(μs=False, setOTAID=True)
+            nickname = 'local_{num}'.format(num=CommonService.RandomStr(6, False))
+            return self.do_register(userID, username, nickname, response, app_bundle_id)
+
+    # 登录
+    def do_login(self, user_qs, response):
+        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
+        userID = user_qs[0].userID
+        print('userID' + userID)
+        tko = TokenObject()
+        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
+        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
+        # 增加角色
+        user_qs[0].role.add(Role.objects.get(rid=1))
+        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
+        # 昵称,邮箱,电话,刷新,头像
+        userIconPath = str(user_list[0]["userIconPath"])
+        if userIconPath and userIconPath.find('static/') != -1:
+            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
+            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
+        else:
+            res['userIconUrl'] = ''
+        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
+        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
+        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
+        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
+        print(res)
+        # 添加用户登录类型
+        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
+        auth_type = 0
+        if oauth_qs.exists():
+            auth_type = oauth_qs[0].authType
+        res['authType'] = auth_type
+        user_qs.update(last_login=now_time, online=True)
+        return response.json(0, res)
+
+    def do_register(self, userID, username, nickname, response, appBundleId):
+        data_valid = DataValid()
+        if data_valid.name_validate(userID) is not True:
+            return response.json(105)
+        try:
+            Device_User.objects.create(
+                username=username,
+                NickName=nickname,
+                password=make_password('123456'),
+                userID=userID,
+                is_active=True,
+                user_isValid=True,
+                is_local=True
+            )
+
+        except Exception as e:
+            errorInfo = traceback.format_exc()
+            print(errorInfo)
+            return response.json(424, repr(e))
+        else:
+            user_qs = Device_User.objects.filter(Q(userID=userID))
+            print('---')
+            print(user_qs)
+            return self.do_login(user_qs, response)
+
+
+def delete_local_account(username):
+    user_qs = Device_User.objects.filter(username=username)
+    print(user_qs)
+    if user_qs.exists():
+        user: Device_User = user_qs[0]
+        if user.is_local:
+            user.delete()
+            Device_Info.objects.filter(userID__userID=user.userID).delete()

+ 1 - 2
Model/models.py

@@ -1,5 +1,4 @@
 from itertools import chain
-from Service.CommonService import CommonService
 from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
 from django.db import models
 from django.utils import six, timezone
@@ -289,7 +288,7 @@ class Equipment_Info(models.Model):
     alarm = models.CharField(blank=True, max_length=256, verbose_name=u'报警信息')
     eventTime = models.CharField(blank=True, default='', max_length=16, verbose_name=u'设备报警时间')
     receiveTime = models.CharField(blank=True, default='', max_length=16, verbose_name=u'接收到报警时间')
-    userID_id = models.CharField(default='',  db_index=True,blank=True, max_length=32, verbose_name=u'用户ID')
+    userID_id = models.CharField(default='',  db_index=True, blank=True, max_length=32, verbose_name=u'用户ID')
     is_st = models.SmallIntegerField(default=0, verbose_name='是否截图')  # 0 否,1 是图,2,视频
     message_id = models.CharField(max_length=32, default='', verbose_name='第三方推送服务器返回的id')
     push_type = models.SmallIntegerField(default=0, verbose_name='第三方推送服务器标志。0:APNS推送,1:谷歌推送,2:极光推送')

+ 2 - 0
Service/CommonService.py

@@ -14,6 +14,7 @@ from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
 
 # 复用性且公用较高封装代码在这
 from Controller.CheckUserData import RandomStr
+from Service.ModelService import ModelService
 
 
 class CommonService:
@@ -99,6 +100,7 @@ class CommonService:
         # ip数据库
         db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
         addr = db.lookup(ip)
+        ModelService.add_tmp_log(addr)
         ts = addr.split('\t')[0]
         return ts
 

+ 9 - 1
Service/ModelService.py

@@ -5,7 +5,6 @@ import requests
 
 from Ansjer.config import BASE_DIR
 from Model.models import *
-from Service.CommonService import CommonService
 import json
 from django.db.models import Q
 
@@ -213,6 +212,15 @@ class ModelService:
         file.flush()
         file.close()
 
+    @staticmethod
+    def add_tmp_log(info):
+        file_path = '/'.join((BASE_DIR, 'static/tmp_test.log'))
+        file = open(file_path, 'a+')
+        file.write("info:" + str(info))
+        file.write('\n')
+        file.flush()
+        file.close()
+
 
 def notify_alexa_delete(userID, UID):
     url = 'https://www.zositech.xyz/deviceStatus/delete'