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

Merge branch 'dev' of http://192.168.136.99:3000/SERVER/AnsjerServer into dev

chanjunkai 5 жил өмнө
parent
commit
9899e58b72

+ 4 - 1
Ansjer/urls.py

@@ -127,6 +127,10 @@ urlpatterns = [
     url(r'^account/loginCode$', UserController.loginCodeView.as_view()),
     url(r'^v3/account/loginByCode$', UserController.v3LoginByCodeView.as_view()),
 
+    # 指纹登录
+    url(r'^v3/account/loginByFingerprint$', UserController.v3LoginByFingerprintView.as_view()),
+    url(r'^v3/account/setFingerprint$', UserController.v3SetFingerprintView.as_view()),
+
     # 新增
     url(r'^detect/detect_group_push$',DetectController.NotificationView.detect_group_push),
     url(r'^detect/add$', DetectController.PushNotificationView.as_view()),
@@ -212,7 +216,6 @@ urlpatterns = [
     url(r'^equipment/flow_test$', EquipmentManager.uid_status_test),
     url(r'^account/appFrequency/(?P<operation>.*)$', UserController.UserAppFrequencyView.as_view()),
     url(r'^v2/userbrand/(?P<operation>.*)$', UserBrandControllerV2.UserBrandV2.as_view()),
-    # url(r'^test/add$', GenerateDataController.GenerateDataView.as_view()),
     url(r'^statistcs/appFrequencyMonth$', StatisticsController.statistcsAppFrequency),
     url(r'^statistcs/appFrequencyYear$', StatisticsController.statistcsAppFrequencyYear),
 

+ 81 - 82
Controller/AdminManage.py

@@ -6,8 +6,7 @@ from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import TemplateView
 from django.utils.decorators import method_decorator
 from django.contrib.auth.hashers import make_password  # 对密码加密模块
-from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel, UserAppFrequencyModel, \
-    AppFrequencyStatisticsModel, AppFrequencyYearStatisticsModel
+from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel
 from Service.ModelService import ModelService
 from django.utils import timezone
 from Model.models import Access_Log, Device_User
@@ -344,86 +343,86 @@ class AdminManage(TemplateView):
         model_data['quantity'] = quantity
         return response.json(0, res)
 
-    def getAppFrequency(self, userID, request_dict, response):
-        own_permission = ModelService.check_perm(userID=userID, permID=30)
-        if own_permission is not True:
-            return response.json(404)
-
-        # 当前的年份
-        current_time = int(time.time())
-        localtime = time.localtime(current_time)
-        current_year = localtime.tm_year
-        current_month = localtime.tm_mon
-
-        start_year = end_year = current_year
-        end_month = current_month
-        start_month = 1
-
-        result = []
-        if end_month != 12:
-            start_month = end_month + 1
-            start_year = current_year - 1
-
-        time_struct = [start_year, start_month, 0, 0, 0, 0, 0, 0, 0]
-        key_formal = '{year}{month}'
-        for i in range(12):
-            result.append({
-                'date_time': key_formal.format(year=time_struct[0], month=str(time_struct[1]).zfill(2)),
-                'data': None
-            })
-
-            month = time_struct[1] + 1
-            if month > 12:
-                time_struct[0] = time_struct[0] + 1
-                time_struct[1] = 1
-            else:
-                time_struct[1] = month
-        #
-        afs_qs = {}
-        if start_year == end_year:
-            afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month, month__lte=end_month).values().order_by('-year', 'month'))
-        else:
-            afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month).values().order_by('-year', 'month'))
-            tmps_qs = list(AppFrequencyStatisticsModel.objects.filter(year=end_year, month__lte=end_month).values().order_by('-year', 'month'))
-            for tmp in tmps_qs:
-                afs_qs.append(tmp)
-
-        tmp_dict = {}
-
-        for afs in afs_qs:
-            key = key_formal.format(year=afs['year'], month=str(afs['month']).zfill(2))
-            tmp_dict[key] = json.loads(afs['data'])
-
-        for res in result:
-            if tmp_dict.__contains__(res['date_time']):
-                res['data'] = tmp_dict[res['date_time']]
-        print(result)
-
-        return response.json(0, result)
-
-    def getAllAppFrequency(self, userID, response):
-        own_permission = ModelService.check_perm(userID=userID, permID=30)
-        if own_permission is not True:
-            return response.json(404)
-
-        # 取出请求年份的统计好的数据
-        print('start')
-        time_struct = time.localtime()
-        current_year = time_struct.tm_year
-        start_year = current_year - 5 + 1
-        afs_qs = AppFrequencyYearStatisticsModel.objects.filter(year__gte=start_year, year__lt=current_year).order_by(
-            '-year')
-        if afs_qs.exists():
-            afs_qs = afs_qs.values('id', 'data', 'num', 'year')
-            res = []
-            for afs in afs_qs:
-                res.append({
-                    'year': afs['year'],
-                    'data': json.loads(afs['data'])
-                })
-            return response.json(0, res)
-        else:
-            return response.json(0, [])
+    # def getAppFrequency(self, userID, request_dict, response):
+    #     own_permission = ModelService.check_perm(userID=userID, permID=30)
+    #     if own_permission is not True:
+    #         return response.json(404)
+    #
+    #     # 当前的年份
+    #     current_time = int(time.time())
+    #     localtime = time.localtime(current_time)
+    #     current_year = localtime.tm_year
+    #     current_month = localtime.tm_mon
+    #
+    #     start_year = end_year = current_year
+    #     end_month = current_month
+    #     start_month = 1
+    #
+    #     result = []
+    #     if end_month != 12:
+    #         start_month = end_month + 1
+    #         start_year = current_year - 1
+    #
+    #     time_struct = [start_year, start_month, 0, 0, 0, 0, 0, 0, 0]
+    #     key_formal = '{year}{month}'
+    #     for i in range(12):
+    #         result.append({
+    #             'date_time': key_formal.format(year=time_struct[0], month=str(time_struct[1]).zfill(2)),
+    #             'data': None
+    #         })
+    #
+    #         month = time_struct[1] + 1
+    #         if month > 12:
+    #             time_struct[0] = time_struct[0] + 1
+    #             time_struct[1] = 1
+    #         else:
+    #             time_struct[1] = month
+    #     #
+    #     afs_qs = {}
+    #     if start_year == end_year:
+    #         afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month, month__lte=end_month).values().order_by('-year', 'month'))
+    #     else:
+    #         afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month).values().order_by('-year', 'month'))
+    #         tmps_qs = list(AppFrequencyStatisticsModel.objects.filter(year=end_year, month__lte=end_month).values().order_by('-year', 'month'))
+    #         for tmp in tmps_qs:
+    #             afs_qs.append(tmp)
+    #
+    #     tmp_dict = {}
+    #
+    #     for afs in afs_qs:
+    #         key = key_formal.format(year=afs['year'], month=str(afs['month']).zfill(2))
+    #         tmp_dict[key] = json.loads(afs['data'])
+    #
+    #     for res in result:
+    #         if tmp_dict.__contains__(res['date_time']):
+    #             res['data'] = tmp_dict[res['date_time']]
+    #     print(result)
+    #
+    #     return response.json(0, result)
+    #
+    # def getAllAppFrequency(self, userID, response):
+    #     own_permission = ModelService.check_perm(userID=userID, permID=30)
+    #     if own_permission is not True:
+    #         return response.json(404)
+    #
+    #     # 取出请求年份的统计好的数据
+    #     print('start')
+    #     time_struct = time.localtime()
+    #     current_year = time_struct.tm_year
+    #     start_year = current_year - 5 + 1
+    #     afs_qs = AppFrequencyYearStatisticsModel.objects.filter(year__gte=start_year, year__lt=current_year).order_by(
+    #         '-year')
+    #     if afs_qs.exists():
+    #         afs_qs = afs_qs.values('id', 'data', 'num', 'year')
+    #         res = []
+    #         for afs in afs_qs:
+    #             res.append({
+    #                 'year': afs['year'],
+    #                 'data': json.loads(afs['data'])
+    #             })
+    #         return response.json(0, res)
+    #     else:
+    #         return response.json(0, [])
 
 
 @require_http_methods(["GET"])

+ 6 - 2
Controller/EquipmentManagerV3.py

@@ -136,13 +136,15 @@ class EquipmentManagerV3(View):
         if userID is None:
             return response.json(309)
         try:
-            deviceData = json.loads(deviceContent)
+            # deviceData = json.loads(deviceContent)
+            deviceData = eval(deviceContent)
             # print(deviceData['View_Password'])
             if deviceData.__contains__('View_Password'):
                 deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
             dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
             dev_info_qs.update(**deviceData)
         except Exception as e:
+            print(e)
             return response.json(177, repr(e))
         else:
             qs = Device_Info.objects.filter(userID_id=userID, id=id)
@@ -316,7 +318,9 @@ class EquipmentManagerV3(View):
                 # return response.json(0, items)
             else:
                 # print('去缓存找数据')
-                redis_value = redis_value.replace("'", '"')
+                print('redis_value: ')
+                print(redis_value)
+                # redis_value = redis_value.replace("'", '"')
                 redis_value = redis_value.replace('"isShare": True', '"isShare": true')
                 redis_value = redis_value.replace('"isShare": False', '"isShare": false')
                 redis_value = redis_value.replace('"isDetector": False', '"isDetector": false')

+ 126 - 2
Controller/UserController.py

@@ -1754,7 +1754,7 @@ class v3LoginView(TemplateView):
         # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
         #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
         users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
-                               'phone', 'password', 'userIconPath')[0]
+                               'phone', 'password', 'userIconPath', 'fingerprint_enable', 'fingerprint_key')[0]
         if not check_password(password, users['password']):
             return response.json(111)
         userID = users['userID']
@@ -1779,6 +1779,8 @@ class v3LoginView(TemplateView):
             res['username'] = users['username'] if users['username'] is not None else ''
             res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
             res['phone'] = users['phone'] if users['phone'] is not None else ''
+            res['fingerprint_enable'] = users['fingerprint_enable']
+            res['fingerprint_key'] = users['fingerprint_key']
             return response.json(0, res)
         else:
             return response.json(tko.code)
@@ -2959,7 +2961,6 @@ class UserAppFrequencyView(TemplateView):
             return response.json(404)
 
     def do_refresh(self, request_dict, userID, response):
-        # return response.json(0)
         type = request_dict.get('type', None)
         month = request_dict.get('month', None)
         if not type or not month:
@@ -3165,3 +3166,126 @@ class v3LoginByCodeView(View):
             return response.json(0, res)
         else:
             return response.json(tko.code)
+
+
+class v3LoginByFingerprintView(View):
+    @method_decorator(csrf_exempt)  # @csrf_exempt
+    def dispatch(self, *args, **kwargs):
+        return super(v3LoginByFingerprintView, self).dispatch(*args, **kwargs)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        lang = request.POST.get('lang', None)
+        if not lang:
+            lang = request.POST.get('language', None)
+        response = ResponseObject(lang)
+        request_dict = request.POST
+
+        was_limited = getattr(request, 'limited', False)
+        if was_limited is True:
+            return response.json(5)
+        return self.validate(request_dict, response)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        lang = request.GET.get('lang', None)
+        if not lang:
+            lang = request.GET.get('language', 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.validate(request_dict, response)
+
+    def validate(self, request_dict, response):
+        password = request_dict.get("password", None)
+
+        if password:
+            password = CommonService.decode_data(password)
+            if password is None:
+                return response.json(444)
+            else:
+                user_qs = Device_User.objects.filter(username=password, is_active=True, user_isValid=True)
+                if not user_qs.exists():
+                    return response.json(104)
+                else:
+                    users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
+                               'phone', 'password', 'userIconPath', 'fingerprint_enable', 'fingerprint_key')[0]
+                    if users['fingerprint_enable'] == 0:
+                        return response.json(112)
+                    else:
+                        userID = users['userID']
+                        tko = TokenObject()
+                        res = tko.generate(
+                            data={'userID': userID, 'lang': response.lang, 'user': users['username'],
+                                  'm_code': '123413243214'})
+                        if tko.code == 0:
+                            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
+                            user_qs.update(last_login=now_time, language=response.lang)
+                            res['rid'] = users['role__rid']
+                            res['roleName'] = users['role__roleName']
+                            res['permList'] = ModelService.own_permission(userID)
+                            res['userID'] = userID
+                            # 昵称,邮箱,电话,刷新,头像
+                            userIconPath = str(users['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'] = users['NickName'] if users['NickName'] is not None else ''
+                            res['username'] = users['username'] if users['username'] is not None else ''
+                            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
+                            res['phone'] = users['phone'] if users['phone'] is not None else ''
+                            res['fingerprint_key'] = CommonService.encode_data(content=users['fingerprint_key'], start=2)
+                            return response.json(0, res)
+                        else:
+                            return response.json(tko.code)
+        else:
+            return response.json(444)
+
+
+class v3SetFingerprintView(View):
+    @method_decorator(csrf_exempt)
+    def dispatch(self, *args, **kwargs):
+        return super(v3SetFingerprintView, self).dispatch(*args, **kwargs)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        return self.validate(request_dict)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        lang = request_dict.get('lang', None)
+        token = request_dict.get('token', None)
+        fingerprint_enable = request_dict.get('fingerprint_enable', None)
+        fingerprint_key = request_dict.get('fingerprint_key', None)
+
+        response = ResponseObject()
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        if not lang:
+            return response.json(444, 'lang')
+
+        response.lang = lang
+
+        data = {}
+
+        if fingerprint_enable:
+            data['fingerprint_enable'] = int(fingerprint_enable)
+
+        if fingerprint_key:
+            data['fingerprint_key'] = CommonService.decode_data(fingerprint_key, end=3)
+
+        if len(data) > 0:
+            Device_User.objects.filter(userID=token.userID).update(**data)
+        return response.json(0)

+ 2 - 0
Controller/shareUserPermission.py

@@ -260,6 +260,8 @@ class shareUserEquipmentView(View):
                             res = {'error_UID': UID, 'Sharing': len(querysetList)}
                         else:
                             res = {'Sharing': len(querysetList)}
+                redisObj = RedisObject(db=8)
+                redisObj.del_data(key='uid_qs_' + GuestID)
                 return response.json(0, res)
 
 

+ 2 - 0
Model/models.py

@@ -147,6 +147,8 @@ class Device_User(AbstractBaseUser):
     language = models.CharField(blank=True, max_length=16, default='en', verbose_name=u'语言地区')
     # 手机注册增加字段
     phone = models.CharField(max_length=16, verbose_name=u'手机号', default='', blank=True)
+    fingerprint_enable = models.SmallIntegerField(default=0, verbose_name=u'是否开启了指纹登录') # 0:未开启,1:已开启
+    fingerprint_key = models.CharField(max_length=128, default='', verbose_name=u'客户端用于解码的密钥等信息')
     objects = UserManager()
 
     USERNAME_FIELD = 'userID'  # 必须有一个唯一标识

+ 2 - 0
Object/ResponseObject.py

@@ -31,6 +31,7 @@ class ResponseObject(object):
             109: 'The password not conform to the rules!',
             110: 'user doesn\'t activated',
             111: 'Error password',
+            112: 'Fingerprint login is not turned on',
             119: 'The qr code has expired',
             120: 'The code has expired',
             121: 'The verification code is wrong!',
@@ -93,6 +94,7 @@ class ResponseObject(object):
             109: '密码格式不符合!',
             110: '用户未激活!',
             111: '密码不正确!',
+            112: '未开通指纹登录',
             119: '二维码过期',
             120: '验证码过期',
             121: '验证码错了!',

+ 19 - 2
Service/CommonService.py

@@ -13,6 +13,9 @@ from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
 
 
 # 复用性且公用较高封装代码在这
+from Controller.CheckUserData import RandomStr
+
+
 class CommonService:
     # 添加模糊搜索
     @staticmethod
@@ -225,9 +228,9 @@ class CommonService:
         return str
 
     @staticmethod
-    def decode_data(content):
+    def decode_data(content, start=1, end=4):
         try:
-            for i in range(1, 4):
+            for i in range(start, end):
                 if i == 1:
                     content = base64.b64decode(content)
                     content = content.decode('utf-8')
@@ -245,3 +248,17 @@ class CommonService:
         except Exception as e:
             print(e)
             return None
+
+    @staticmethod
+    def encode_data(content, start=1, end=4):
+        for i in range(start, end):
+            if i == 1:
+                content = RandomStr(3, False)+content+RandomStr(3, False)
+                content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
+            if i == 2:
+                content = RandomStr(2, False)+str(content)+RandomStr(2, False)
+                content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
+            if i == 3:
+                content = RandomStr(1, False)+str(content)+RandomStr(1, False)
+                content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
+        return content