Browse Source

添加一个字段,和修改接口

pengzhibo168 5 years ago
parent
commit
9d8cdd578f

+ 1 - 1
Ansjer/urls.py

@@ -182,7 +182,7 @@ urlpatterns = [
     url(r'^appset/(?P<operation>.*)$', AppSetController.AppSetView.as_view()),
     url(r'^appset/(?P<operation>.*)$', AppSetController.AppSetView.as_view()),
     url(r'^application/(?P<operation>.*)$', ApplicationController.ApplicationView.as_view()),
     url(r'^application/(?P<operation>.*)$', ApplicationController.ApplicationView.as_view()),
     url(r'^login/oauth/(?P<operation>.*)$', ApplicationController.AuthView.as_view()),
     url(r'^login/oauth/(?P<operation>.*)$', ApplicationController.AuthView.as_view()),
-
+    url(r'^grant/code/(?P<operation>.*)$', ApplicationController.GrantCodeView.as_view()),
 
 
     # app 设备消息模板
     # app 设备消息模板
     # 路由加参数参考
     # 路由加参数参考

+ 83 - 22
Controller/ApplicationController.py

@@ -20,12 +20,11 @@ from Object.RedisObject import RedisObject
 from Object.TokenObject import TokenObject
 from Object.TokenObject import TokenObject
 from Service.ModelService import ModelService
 from Service.ModelService import ModelService
 from Service.CommonService import CommonService
 from Service.CommonService import CommonService
-from django.http import JsonResponse
+from django.http import JsonResponse, HttpResponseRedirect
 from django.contrib import auth
 from django.contrib import auth
 import time,json
 import time,json
 from Object.ResponseObject import ResponseObject
 from Object.ResponseObject import ResponseObject
-    # http://192.168.136.39:8000/login/oauth/authorize
-
+# http://192.168.136.39:8000/login/oauth/authorize
 # http://192.168.136.39:8000/application/query
 # http://192.168.136.39:8000/application/query
 class AuthView(View):
 class AuthView(View):
     def get(self, request, *args, **kwargs):
     def get(self, request, *args, **kwargs):
@@ -65,6 +64,7 @@ class AuthView(View):
         client_id = request_dict.get("client_id", '')
         client_id = request_dict.get("client_id", '')
         response_type = request_dict.get("response_type", '')
         response_type = request_dict.get("response_type", '')
         scope = request_dict.get("scope", '')
         scope = request_dict.get("scope", '')
+        app_id = request_dict.get("app_id", '')
         redirect_uri = request_dict.get("redirect_uri", '')
         redirect_uri = request_dict.get("redirect_uri", '')
         client_secret = request_dict.get("client_secret", '')
         client_secret = request_dict.get("client_secret", '')
         token = request_dict.get('token', None)
         token = request_dict.get('token', None)
@@ -80,11 +80,16 @@ class AuthView(View):
             nowTime = int(time.time())
             nowTime = int(time.time())
             user_qs = GrantCodeModel.objects.filter(userID__userID=userID)
             user_qs = GrantCodeModel.objects.filter(userID__userID=userID)
             code = CommonService.encrypt_data(randomlength=32)
             code = CommonService.encrypt_data(randomlength=32)
-            Application = ApplicationModel.objects.filter(client_id=client_id)
-            if Application.exists():
-                print(Application.exists())
+            application = ApplicationModel.objects.filter(client_id=client_id)
+
+            if application.exists():
+                print(application.exists())
             else:
             else:
-                return JsonResponse({'error': 'config error,client_id This value is wrong'})
+                return response.json(10005)
+
+            if application[0].redirect_uri != redirect_uri:
+                return response.json(10006)
+
             if not user_qs.exists():
             if not user_qs.exists():
                 print('在创建')
                 print('在创建')
                 try:
                 try:
@@ -92,6 +97,7 @@ class AuthView(View):
                         userID=Device_User.objects.get(userID=userID),
                         userID=Device_User.objects.get(userID=userID),
                         application=ApplicationModel.objects.get(client_id=client_id),
                         application=ApplicationModel.objects.get(client_id=client_id),
                         code=code,
                         code=code,
+                        app_id=app_id,
                         expire_time=nowTime+3600,
                         expire_time=nowTime+3600,
                         add_time=nowTime,
                         add_time=nowTime,
                         update_time=nowTime)
                         update_time=nowTime)
@@ -102,13 +108,16 @@ class AuthView(View):
                     return response.json(178)
                     return response.json(178)
             else:
             else:
                 print('在修改')
                 print('在修改')
-                user_qs.update(code=code,update_time=nowTime,expire_time=nowTime+3600)
+                user_qs.update(code=code, app_id=app_id, update_time=nowTime, expire_time=nowTime+3600)
+
             redirect_uri = redirect_uri + '?code=' + code + '&state=' + state
             redirect_uri = redirect_uri + '?code=' + code + '&state=' + state
+            if application[0].skip_auth:
+                return HttpResponseRedirect(redirect_uri)
             return response.json(0, {'url': redirect_uri})
             return response.json(0, {'url': redirect_uri})
         else:
         else:
             return response.json(tko.code)
             return response.json(tko.code)
 
 
-        # 增加对code和client_id的校验代码,返回access_token和refresh_token
+    # 增加对code和client_id,client_secret的校验代码,返回access_token和refresh_token
     def do_token(self,request_dict, response, content_range):
     def do_token(self,request_dict, response, content_range):
         code = request_dict.get("code", None)
         code = request_dict.get("code", None)
         print('code:')
         print('code:')
@@ -124,7 +133,7 @@ class AuthView(View):
             str_all = str.split(":", 1)
             str_all = str.split(":", 1)
             client_id = str_all[0]
             client_id = str_all[0]
             client_secret = str_all[1]
             client_secret = str_all[1]
-            eq = ApplicationModel.objects.filter(client_secret=client_secret)
+            eq = ApplicationModel.objects.filter(client_secret=client_secret, client_id=client_id)
             if eq.exists():
             if eq.exists():
                 access_token = code
                 access_token = code
                 refresh_token = CommonService.encrypt_data(randomlength=32)
                 refresh_token = CommonService.encrypt_data(randomlength=32)
@@ -138,9 +147,9 @@ class AuthView(View):
                 print(res_json)
                 print(res_json)
                 return JsonResponse(res_json)
                 return JsonResponse(res_json)
             else:
             else:
-                return JsonResponse({'error': 'client_secret This value is misconfigured.'})
+                return response.json(10001)
         else:
         else:
-            return JsonResponse({'error': 'Check your configuration:no client_id,client_secret'})
+            return response.json(10002)
 
 
     def do_user(self, request_dict, response,content_range):
     def do_user(self, request_dict, response,content_range):
         str = content_range
         str = content_range
@@ -158,14 +167,9 @@ class AuthView(View):
                 return JsonResponse(res_json)
                 return JsonResponse(res_json)
             else:
             else:
                 print('没有找到数据')
                 print('没有找到数据')
-                return JsonResponse({'error': 'token inexistence'})
+                return response.json(10003)
         else:
         else:
-            return JsonResponse({'error': 'The request method is not correct. Please contact the administrator.'})
-
-
-
-
-
+            return response.json(10004)
 
 
 
 
 class ApplicationView(View):
 class ApplicationView(View):
@@ -202,7 +206,6 @@ class ApplicationView(View):
         if own_perm is not True:
         if own_perm is not True:
             return response.json(404)
             return response.json(404)
         # http://192.168.136.39:8000/application/add?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxMzgwMDEzODAwMSIsImxhbmciOiJjbiIsInVzZXIiOiIxMzgwMDEzODAwMSIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImV4cCI6MTU4NzYxNjQ0NX0.BIwq - eWDcTnqLBTxqpi7BgJoU9TeIHC5Ibc2LUUJPls&name=pzb&client_id=pzb12345&client_secret=pzb12345678&client_type=confidential&grant_type=authorization_code&redirect_uri=https://www.zositech.cn&skip_auth=1
         # http://192.168.136.39:8000/application/add?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxMzgwMDEzODAwMSIsImxhbmciOiJjbiIsInVzZXIiOiIxMzgwMDEzODAwMSIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImV4cCI6MTU4NzYxNjQ0NX0.BIwq - eWDcTnqLBTxqpi7BgJoU9TeIHC5Ibc2LUUJPls&name=pzb&client_id=pzb12345&client_secret=pzb12345678&client_type=confidential&grant_type=authorization_code&redirect_uri=https://www.zositech.cn&skip_auth=1
-
         nowTime = int(time.time())
         nowTime = int(time.time())
         name = request_dict.get('name', None)
         name = request_dict.get('name', None)
         client_id = request_dict.get('client_id', None)
         client_id = request_dict.get('client_id', None)
@@ -218,8 +221,6 @@ class ApplicationView(View):
         except Exception:
         except Exception:
             return response.json(178)
             return response.json(178)
 
 
-
-
     def query(self, request_dict, userID, response):
     def query(self, request_dict, userID, response):
         own_perm = ModelService.check_perm(userID, 20)
         own_perm = ModelService.check_perm(userID, 20)
         if own_perm is True:
         if own_perm is True:
@@ -278,3 +279,63 @@ class ApplicationView(View):
             return response.json(173)
             return response.json(173)
 
 
 
 
+class GrantCodeView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        return self.validation(request.GET, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        return self.validation(request.POST, operation)
+
+    def validation(self, request_dict, operation):
+        response = ResponseObject()
+        token = request_dict.get('token', None)
+        tko = TokenObject(token)
+        if tko.code == 0:
+            userID = tko.userID
+            if operation == 'query':
+                return self.query(request_dict, userID, response)
+            elif operation == 'delete':
+                return self.delete(request_dict, userID, response)
+            else:
+                return response.json(414)
+        else:
+            return response.json(tko.code)
+
+
+    def query(self, request_dict, userID, response):
+        own_perm = ModelService.check_perm(userID, 20)
+        if own_perm is True:
+            page = int(request_dict.get('page', 0))
+            line = int(request_dict.get('line', 0))
+            if page == 0:
+                page=1
+            if line == 0:
+                line=10
+            gc = GrantCodeModel.objects.filter()
+            if gc.exists():
+                count = gc.count()
+                res = gc[(page - 1) * line:page * line].values('id', 'userID', 'userID__username', 'userID__userEmail', 'userID__NickName', 'userID__language', 'userID__phone', 'code', 'app_id', 'application', 'add_time', 'update_time')
+                send_json = CommonService.qs_to_list(res)
+                return response.json(0, {'datas': send_json, 'count': count})
+            else:
+                return response.json(0, {'datas': [], 'count': 0})
+        else:
+            return response.json(404)
+
+
+    def delete(self, request_dict, userID, response):
+        own_perm = ModelService.check_perm(userID=userID, permID=10)
+        if own_perm is not True:
+            return response.json(404)
+        id = request_dict.get('id', None)
+        uid_set = GrantCodeModel.objects.filter(id=id)
+        if uid_set.exists():
+            uid_set.delete()
+            return response.json(0)
+        else:
+            return response.json(173)
+

+ 2 - 1
Model/models.py

@@ -2,7 +2,7 @@ from itertools import chain
 from Service.CommonService import CommonService
 from Service.CommonService import CommonService
 from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
 from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
 from django.db import models
 from django.db import models
-from django.utils import six
+from django.utils import six, timezone
 from django.utils.encoding import python_2_unicode_compatible
 from django.utils.encoding import python_2_unicode_compatible
 from imagekit.models import ProcessedImageField
 from imagekit.models import ProcessedImageField
 from imagekit.processors import ResizeToFill
 from imagekit.processors import ResizeToFill
@@ -833,6 +833,7 @@ class GrantCodeModel(models.Model):
     id = models.BigAutoField(primary_key=True)
     id = models.BigAutoField(primary_key=True)
     userID = models.ForeignKey(Device_User, verbose_name="用户表userID", to_field='userID', on_delete=models.CASCADE)
     userID = models.ForeignKey(Device_User, verbose_name="用户表userID", to_field='userID', on_delete=models.CASCADE)
     code = models.CharField(max_length=32, unique=True)
     code = models.CharField(max_length=32, unique=True)
+    app_id = models.CharField(max_length=100, default='',verbose_name="appBundleId")
     application = models.ForeignKey(ApplicationModel,verbose_name="用户表id", to_field='id', on_delete=models.CASCADE)
     application = models.ForeignKey(ApplicationModel,verbose_name="用户表id", to_field='id', on_delete=models.CASCADE)
     expire_time = models.IntegerField(verbose_name='过期时间', default=0)
     expire_time = models.IntegerField(verbose_name='过期时间', default=0)
     add_time = models.IntegerField(verbose_name='添加时间', default=0)
     add_time = models.IntegerField(verbose_name='添加时间', default=0)

+ 12 - 0
Object/ResponseObject.py

@@ -62,6 +62,12 @@ class ResponseObject(object):
             904: 'Version does not support this feature!',
             904: 'Version does not support this feature!',
             906: 'Cause of file operation error',
             906: 'Cause of file operation error',
             907: 'The download file does not exist!',
             907: 'The download file does not exist!',
+            10001: 'Customer number, customer confidentiality error',
+            10002: 'Check your configuration: no customer number, customer confidentiality',
+            10003: 'The authorization code does not exist. Please reauthorize',
+            10004: 'The request method is incorrect. Please contact the developer',
+            10005: 'Wrong configuration, wrong customer number',
+            10006: 'Configuration error. The path value is incorrect',
         }
         }
         data_cn = {
         data_cn = {
             0: '成功',
             0: '成功',
@@ -118,6 +124,12 @@ class ResponseObject(object):
             904: '版本不支持本功能!',
             904: '版本不支持本功能!',
             906: '文件操作错误',
             906: '文件操作错误',
             907: '文件不存在!',
             907: '文件不存在!',
+            10001: '客户编号,客户机密错误',
+            10002: '检查您的配置:没有客户编号,客户机密',
+            10003: '授权码不存在,请重新授权',
+            10004: '请求方法不正确。请联系开发者',
+            10005: '配置错误,客户编号这个值是错误的',
+            10006: '配置错误,路径这个值是错误的',
         }
         }
         if self.lang == 'cn':
         if self.lang == 'cn':
             msg = data_cn
             msg = data_cn

+ 14 - 12
Service/CommonService.py

@@ -13,7 +13,6 @@ from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
 
 
 # 复用性且公用较高封装代码在这
 # 复用性且公用较高封装代码在这
 class CommonService:
 class CommonService:
-
     # 添加模糊搜索
     # 添加模糊搜索
     @staticmethod
     @staticmethod
     def get_kwargs(data={}):
     def get_kwargs(data={}):
@@ -176,17 +175,20 @@ class CommonService:
         res = []
         res = []
         # print(qs)
         # print(qs)
         for ps in qs:
         for ps in qs:
-            if 'add_time' in ps:
-                ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
-            if 'update_time' in ps:
-                ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
-            if 'end_time' in ps:
-                ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
-            if 'data_joined' in ps:
-                if ps['data_joined']:
-                    ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
-                else:
-                    ps['data_joined'] = ''
+            try:
+                if 'add_time' in ps:
+                    ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
+                if 'update_time' in ps:
+                    ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
+                if 'end_time' in ps:
+                    ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
+                if 'data_joined' in ps:
+                    if ps['data_joined']:
+                        ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
+                    else:
+                        ps['data_joined'] = ''
+            except Exception as e:
+                pass
             res.append(ps)
             res.append(ps)
         return res
         return res
 
 

+ 4 - 1
Service/TemplateService.py

@@ -65,7 +65,10 @@ class TemplateService:
             'detect/changeStatus',
             'detect/changeStatus',
             # 'notify/push',
             # 'notify/push',
             'equipment/flowUpdate',
             'equipment/flowUpdate',
-            'wechat/authsign'
+            'wechat/authsign',
+            'login/oauth/authorize',
+            'login/oauth/access_token',
+            'login/oauth/user'
         ]
         ]
         return apiList
         return apiList