CrazyIter_Bin 2 năm trước cách đây
mục cha
commit
e5ee26bc49

+ 4 - 4
TEAMModelBI/Controllers/BINormal/BusinessController.cs

@@ -20,13 +20,13 @@ namespace TEAMModelBI.Controllers.BINormal
 {
     [Route("bizconfig")]
     [ApiController]
-    public class BusinessController : ControllerBase
+    public class BusinessConfigController : ControllerBase
     {
         public readonly AzureCosmosFactory _azureCosmos;
         public readonly AzureStorageFactory _azureStorage;
         public readonly DingDing _dingDing;
         public readonly Option _option;
-        public BusinessController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
+        public BusinessConfigController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
         {
             _azureCosmos = azureCosmos;
             _azureStorage = azureStorage;
@@ -63,7 +63,7 @@ namespace TEAMModelBI.Controllers.BINormal
             {
                 bizConfig.id = Guid.NewGuid().ToString();
                 bizConfig.code = "BizConfig";
-                bizConfig.pk = "Business";
+                bizConfig.pk = "BizConfig";
                 bizConfig.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                 var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, "business");
                 bizConfig.jti = auth_token.jti;
@@ -108,7 +108,7 @@ namespace TEAMModelBI.Controllers.BINormal
                     using var json = await JsonDocument.ParseAsync(response.ContentStream);
                     BizConfig tempBizConfig = json.ToObject<BizConfig>();
 
-                    bizConfig.pk = "Business";
+                    bizConfig.pk = "BizConfig";
                     bizConfig.code = "BizConfig";
                     bizConfig.ttl = -1;
 

+ 1 - 1
TEAMModelBI/Controllers/BINormal/BusinessUsersController.cs

@@ -110,7 +110,7 @@ namespace TEAMModelBI.Controllers.BINormal
                     using var json = await JsonDocument.ParseAsync(response.ContentStream);
                     BizUsers tempbizUsers = json.ToObject<BizUsers>();
 
-                    bizUsers.pk = "Business";
+                    bizUsers.pk = "BizUsers";
                     bizUsers.code = "BizUsers";
                     bizUsers.ttl = -1;
                     bizUsers.relation = tempbizUsers.relation;

+ 59 - 24
TEAMModelOS.SDK/Context/Attributes/Filter/ApiTokenAttribute.cs

@@ -13,6 +13,9 @@ using System.IO;
 using System.Reflection;
 using Microsoft.Extensions.Primitives;
 using TEAMModelOS.SDK.Models.Table;
+using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
+using System.Text.Json;
+using HTEXLib.COMM.Helpers;
 
 namespace TEAMModelOS.Filter
 {
@@ -78,7 +81,8 @@ namespace TEAMModelOS.Filter
             var option = services.GetService<IOptions<Option>>();
             var azureRedis = services.GetService<AzureRedisFactory>();
             var azureStorage = services.GetService<AzureStorageFactory>();
-            return new InternalAuthTokenFilter(option ,azureRedis, azureStorage, Auth,   Limit);
+            var azureCosmos = services.GetService<AzureCosmosFactory>();
+            return new InternalAuthTokenFilter(azureCosmos ,  option ,azureRedis,  Auth,   Limit);
         }
 
         private class InternalAuthTokenFilter : IResourceFilter
@@ -88,15 +92,14 @@ namespace TEAMModelOS.Filter
             private readonly string _auth;
             private readonly bool _limit;
             private readonly AzureRedisFactory _azureRedis;
-            private readonly AzureStorageFactory _azureStorage  ;
-
-            public InternalAuthTokenFilter(IOptions<Option> option, AzureRedisFactory azureRedis, AzureStorageFactory  azureStorage, string auth, bool limit)
+            private readonly AzureCosmosFactory _azureCosmos;
+            public InternalAuthTokenFilter(AzureCosmosFactory azureCosmos,IOptions<Option> option, AzureRedisFactory azureRedis,   string auth, bool limit)
             {
                 _option = option.Value;
                 _auth = auth;
                 _limit = limit;
                 _azureRedis = azureRedis;
-                _azureStorage = azureStorage;
+                _azureCosmos=azureCosmos;
             }
             public void OnResourceExecuting(ResourceExecutingContext context)
             {
@@ -113,6 +116,8 @@ namespace TEAMModelOS.Filter
                         scope = paths[0];
                     }
                 }
+                string msg = "";
+                int code = 0;
                 if (scope.Equals("school") ||scope.Equals("business"))
                 {
                     string id = string.Empty, school = string.Empty, jti = string.Empty;
@@ -123,8 +128,10 @@ namespace TEAMModelOS.Filter
                     {
                         var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
                         string iss = jwt.Payload.Iss; //iss 检查jwt是否是测试站,正式站的授权key 
-                        string tokenScope= jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("scope"))?.Value;
-                        //if (tokenScope.Equals(scope)) {
+                        string tokenScope = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("scope"))?.Value;
+                        //访问的jwt的tokenScope 是否与访问的接口一致。
+                        if (tokenScope.Equals(scope))
+                        {
 
                             var keys = OpenApiJtwIssuer.OpenApiJtw签发者.GetDescriptionText().Split(',');
                             string issuer = "";
@@ -162,7 +169,7 @@ namespace TEAMModelOS.Filter
                                     //school = jwt.Payload.Azp;//学校编码
                                     //如果是商务合作模式 则需要手动获取学校编码
                                     school = context.HttpContext.GetXAuth("School");
-#if !DEBUG
+#if DEBUG
                                     var permissions = jwt.Claims.Where(c => c.Type.Equals("auth"));
                                     ///当前请求的api的设置的permission值是否包含在 从jwt的获取["1","2","3","4","5"]值中
                                     if (!string.IsNullOrWhiteSpace(_auth) && permissions.Count() > 0)
@@ -171,9 +178,16 @@ namespace TEAMModelOS.Filter
                                         {
                                             pass = true;
                                         }
+                                        else {
+                                            msg = "当前访问的接口不在已授权的接口范围内!";
+                                            code = 401001;
+                                        }
+                                    }
+                                    else {
+                                        msg = "token未设置可访问的接口!"; code = 401002;
                                     }
 #else
-                                pass = true;
+                                    pass = true;
 #endif
                                 }
                                 else if (scope.Equals("business"))
@@ -186,31 +200,47 @@ namespace TEAMModelOS.Filter
                                     {
                                         pass = true;
                                     }
-                                    else {
+                                    else
+                                    {
                                         //如果访问的接口是 business/get-schools
                                         if (!string.IsNullOrWhiteSpace(XAuthSchool))
                                         {
-                                            var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-                                            List<BusinessSchool> schools =   table.FindListByDictSync<BusinessSchool>(new Dictionary<string, object> { { "PartitionKey", $"BusinessSchool" } ,{ "school", XAuthSchool },{ "bizid" ,id} });
-                                            List<BusinessConfig> configs = table.FindListByDictSync<BusinessConfig>(new Dictionary<string, object> { { "PartitionKey", $"BusinessConfig" }, { "RowKey", id } });
-                                            //同时授权学校存在,且jti一致 ,验证jti原因在于 token轮换或刷新后,旧的token不能再使用。
-                                            if (schools.Any() && configs.Any())
+                                            var  response = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(id ,new Azure.Cosmos.PartitionKey("BizConfig")).Result ;
+                                            if (response.Status == 200)
                                             {
-                                                if (configs[0].jti.Equals(jti)) {
-                                                    pass = true;
-                                                    school = XAuthSchool;
+                                                BizConfig bizConfig = JsonDocument.Parse(response.Content).Deserialize<BizConfig>() ;
+                                                if (bizConfig.schools.IsNotEmpty()  && bizConfig.schools.Select(z=>z.id).Contains(XAuthSchool))
+                                                {
+                                                    if (bizConfig.jti.Equals(jti))
+                                                    {
+                                                        school = XAuthSchool;
+                                                        pass = true;
+                                                    }
+                                                    else {
+                                                        msg = "当前Token已经失效!"; code = 401003;
+                                                        pass = false;
+                                                    }
+                                                }
+                                                else {
+                                                    msg = "未开通学校数据访问授权!"; code = 401004;
+                                                    pass = false;
                                                 }
                                             }
                                             else {
+                                                msg = "企业信息不存在!"; code = 401005;
                                                 pass = false;
                                             }
                                         }
                                         else
                                         {
+                                            msg = "学校编码为空!"; code = 401006;
                                             pass = false;
                                         }
                                     }
                                 }
+                                else {
+                                    msg = "访问的接口不在学校或第三方业务范围内!"; code = 401007;
+                                }
                                 if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(school) && !string.IsNullOrEmpty(jti))
                                 {
                                     //AIP 开启限流策略 处理限流问题
@@ -219,7 +249,13 @@ namespace TEAMModelOS.Filter
                                     }
                                 }
                             }
-                        //}
+                        }
+                        else {
+                            msg = "token的scope与接口的业务类型不匹配!"; code = 401008;
+                        }
+                    }
+                    else {
+                        msg = "token error!"; code = 401009;
                     }
                     if (pass)
                     {
@@ -228,16 +264,15 @@ namespace TEAMModelOS.Filter
                     }
                     else
                     {
-                        JsonResult jsonResult = new JsonResult(new { });
+                        JsonResult jsonResult = new JsonResult(new {  msg,code});
                         jsonResult.StatusCode = 401;
                         context.Result = jsonResult;
-                      
-
-                       
                     }
                 }
                 else {
-                    JsonResult jsonResult = new JsonResult(new { });
+                    msg = "该接口暂未授权访问!";
+                    code = 401010;
+                    JsonResult jsonResult = new JsonResult(new { msg,code});
                     jsonResult.StatusCode = 401;
                     context.Result = jsonResult;
                 }

+ 41 - 36
TEAMModelOS.SDK/DI/HttpTrigger/WebHookHttpTrigger.cs

@@ -20,6 +20,7 @@ using TEAMModelOS.SDK;
 using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Models;
+using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
 using TEAMModelOS.SDK.Models.Cosmos.Teacher;
 using TEAMModelOS.SDK.Models.Table;
 using static TEAMModelOS.SDK.Models.Teacher;
@@ -51,7 +52,7 @@ namespace TEAMModelOS.SDK.DI
         public async Task<HttpResponseData> NoticeSchoolAuthChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "webhook/school-auth-change")] HttpRequestData request)
         {
             var response = request.CreateResponse(HttpStatusCode.OK);
-            (  List<BusinessConfig> businessConfigs, List<string> webhookdomain, SchoolAuthChange data) = await GetRequestData<SchoolAuthChange>(request);
+            (  List<BizConfig> businessConfigs, List<string> webhookdomain, SchoolAuthChange data) = await GetRequestData<SchoolAuthChange>(request);
             if (webhookdomain.IsNotEmpty())
             {
                 foreach (var domain in webhookdomain)
@@ -88,7 +89,7 @@ namespace TEAMModelOS.SDK.DI
         [ApiToken(Auth = "1201", Name = "名单成员变更", RWN = "N")]
         public async Task<HttpResponseData> NoticeGroupChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "webhook/group-member-change")] HttpRequestData request) {
             var response = request.CreateResponse(HttpStatusCode.OK);
-            (  List < BusinessConfig > businessConfigs, List<string> webhookdomain, GroupChange data) = await  GetRequestData<GroupChange>(request);
+            (  List < BizConfig > businessConfigs, List<string> webhookdomain, GroupChange data) = await  GetRequestData<GroupChange>(request);
 
             if (    webhookdomain.IsNotEmpty()&& string.IsNullOrWhiteSpace(data.school)) {
                 foreach (var domain in webhookdomain) {
@@ -155,48 +156,52 @@ namespace TEAMModelOS.SDK.DI
         /// <typeparam name="T"></typeparam>
         /// <param name="request"></param>
         /// <returns></returns>
-        public async Task<( List<BusinessConfig> businessConfigs,List<string> webhookdomain, T data)> GetRequestData<T>(HttpRequestData request)
+        public async Task<( List<BizConfig> businessConfigs,List<string> webhookdomain, T data)> GetRequestData<T>(HttpRequestData request)
         {
             //var response = request.CreateResponse(HttpStatusCode.OK);
             string data = await new StreamReader(request.Body).ReadToEndAsync();
             var json = JsonDocument.Parse(data).RootElement;
-            string school = null;
-            List<BusinessConfig> businessConfigs = null ;
-            var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-            if (json.TryGetProperty("school", out JsonElement _school))
-            {
-                school = _school.GetString();
-               
-                List<BusinessSchool> schools = table.FindListByDictSync<BusinessSchool>(new Dictionary<string, object> { { "PartitionKey", $"BusinessSchool" }, { "school", school } });
-                var bizid = schools.Select(x => x.bizid).ToList();
-                List<string> Codes = new List<string>();
-                bizid.ForEach(x => {
-                    Codes.Add($" RowKey {QueryComparisons.Equal} '{x}' ");
-                });
-                string tbqurey = $"PartitionKey {QueryComparisons.Equal} 'BusinessConfig'  and ( {string.Join(" or ", Codes)} )  ";
-                var result = await table.ExecuteQuerySegmentedAsync(new TableQuery<BusinessConfig>().Where(tbqurey), null);
-                if (result != null) {
-                    businessConfigs= result.Results;
+            List< BizConfig > bizConfigs = new List< BizConfig >();
+            try {
+                var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
+                if (json.TryGetProperty("school", out JsonElement _school) && !string.IsNullOrWhiteSpace($"{_school}"))
+                {
+                    string sql = $"select distinct value c from c join s in c.schools where s.id='{_school}' ";
+
+                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal)
+                        .GetItemQueryIterator<BizConfig>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("BizConfig") }))
+                    {
+                        bizConfigs.Add(item);
+                    }
                 }
-            }
-            if (json.TryGetProperty("bizid", out JsonElement _bizid)) {
-                string tbqurey = $"PartitionKey {QueryComparisons.Equal} 'BusinessConfig'  and  RowKey {QueryComparisons.Equal} '{_bizid}' ";
-                var result = await table.ExecuteQuerySegmentedAsync(new TableQuery<BusinessConfig>().Where(tbqurey), null);
-                if (result != null)
+                if (json.TryGetProperty("bizid", out JsonElement _bizid))
+                {
+                    try
+                    {
+                        BizConfig bizConfig = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReadItemAsync<BizConfig>($"{_bizid}", new PartitionKey("BizConfig"));
+                        bizConfigs.Add(bizConfig);
+                    }
+                    catch (CosmosException ex) when (ex.Status == 404)
+                    {
+                        return (bizConfigs, null, default(T));
+                    }
+                }
+                if (json.TryGetProperty("data", out JsonElement _data) && bizConfigs.IsNotEmpty())
                 {
-                    businessConfigs = result.Results;
+                    var webhookdomain = bizConfigs.Where(z => !string.IsNullOrWhiteSpace(z.webhook)).ToList();
+                    List<string> webhookdomains = new List<string>();
+                    webhookdomain.ForEach(x => {
+                        webhookdomains.AddRange(x.webhook.Split(",").Select(y => x.https == 1 ? $"https://{y}" : $"http://{y}"));
+                    });
+                    return (bizConfigs, webhookdomains, _data.ToObject<T>());
                 }
+                else 
+                { 
+                    return (bizConfigs, null, default(T)); 
+                }
+            } catch {
+                return (bizConfigs, null, default(T));
             }
-            if (json.TryGetProperty("data", out JsonElement _data)  && businessConfigs.IsNotEmpty())
-            {
-                var webhookdomain =  businessConfigs.Where(z => !string.IsNullOrWhiteSpace(z.webhook)).ToList();
-                List<string> webhookdomains = new List<string>();
-                webhookdomain.ForEach(x => {
-                    webhookdomains.AddRange(x.webhook.Split(",").Select(y =>x.https==1? $"https://{y}":$"http://{y}"));
-                });
-                return ( businessConfigs, webhookdomains, _data.ToObject<T>());
-            }
-            else { return (   businessConfigs,null , default(T)); }
         }
     }
    

+ 2 - 2
TEAMModelOS.SDK/Models/Cosmos/BI/BINormal/BizConfig.cs

@@ -14,7 +14,7 @@ namespace TEAMModelOS.SDK.Models.Cosmos.BI.BINormal
     {
         public BizConfig()
         {
-            pk = "Business";
+            pk = "BizConfig";
         }
         /// <summary>
         /// 合作方名称
@@ -86,7 +86,7 @@ namespace TEAMModelOS.SDK.Models.Cosmos.BI.BINormal
     {
         public BizUsers() 
         {
-            pk = "Business";
+            pk = "BizUsers";
         }
 
         /// <summary>

+ 8 - 11
TEAMModelOS/Controllers/OpenApi/Init/OpenApiConfigController.cs

@@ -14,6 +14,7 @@ using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Models;
 using TEAMModelOS.SDK.Models.Cosmos;
+using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
 using TEAMModelOS.SDK.Models.Table;
 
 namespace TEAMModelOS.Controllers
@@ -52,18 +53,14 @@ namespace TEAMModelOS.Controllers
             try
             {
                 if (!request.TryGetProperty("id", out JsonElement _id)) { return BadRequest(); }
-                var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-                List<BusinessConfig> configs = table.FindListByDictSync<BusinessConfig>(new Dictionary<string, object> { { "PartitionKey", $"BusinessConfig" }, { "RowKey", $"{_id}" } });
+               
+                BizConfig bizConfig = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReadItemAsync<BizConfig>($"{_id}", new PartitionKey("BizConfig"));
                 string jwt = "";
-                if (configs.Any())
-                {
-                    var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, configs[0].RowKey, _option.JwtSecretKey, "business");
-                    jwt = auth_token.jwt;
-                    configs[0].jti = auth_token.jti;
-                    configs[0].token = auth_token.jwt;
-                    await table.SaveOrUpdate<BusinessConfig>(configs[0]);
-                }
-
+                var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, "business");
+                jwt = auth_token.jwt;
+                bizConfig.jti = auth_token.jti;
+                bizConfig.token = auth_token.jwt;
+                await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
                 return Ok(new { jwt });
             }
             catch (Exception e)

+ 1 - 1
TEAMModelOS/Controllers/System/OpenApiController.cs

@@ -192,7 +192,7 @@ namespace TEAMModelOS.Controllers
                     var info = json.ToObject<OpenApp>();
                     //创建Token
                     //域名  应用的id, jwtkey  学校编码
-                    var auth_token = JwtAuthExtension.CreateSchoolApiToken(_option.HostName, info.id, _option.JwtSecretKey,info.name, info.auths, info.school);
+                    var auth_token = JwtAuthExtension.CreateSchoolApiToken(_option.Location, info.id, _option.JwtSecretKey,info.name, info.auths, info.school);
                     info.token = auth_token.jwt;
                     info.jti = auth_token.jti;
                     info = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}"));