소스 검색

BI项目导入

Li 3 년 전
부모
커밋
56323c851a

+ 46 - 0
TEAMModeBI/Controllers/LoginController.cs

@@ -0,0 +1,46 @@
+using Azure.Cosmos;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.DI;
+using TEAMModelOS.SDK.Models;
+
+namespace TEAMModeBI.Controllers
+{
+    [ProducesResponseType(StatusCodes.Status200OK)]
+    [ProducesResponseType(StatusCodes.Status400BadRequest)]
+    [Route("common/login")]
+    [ApiController]
+    public class LoginController : ControllerBase
+    {
+        private readonly AzureCosmosFactory _azureCosmos;
+        public LoginController(AzureCosmosFactory azureCosmos)
+        {
+            _azureCosmos = azureCosmos;
+           
+        }
+
+        /// <summary>
+        /// 修改教师信息
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("dingding")]
+        public async Task<IActionResult> SetTeacherInfo(JsonElement request) {
+            var client = _azureCosmos.GetCosmosClient();
+            if (!request.TryGetProperty("code", out JsonElement _code))
+            {
+                return BadRequest();
+            }
+
+
+            Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{_code}", new PartitionKey("Base"));
+            return Ok(new { teacher = teacher });
+        }
+    }
+}

+ 78 - 1
TEAMModeBI/Startup.cs

@@ -1,3 +1,4 @@
+using Microsoft.AspNetCore.Authentication.JwtBearer;
 using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Mvc;
@@ -5,19 +6,29 @@ using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
+using Microsoft.IdentityModel.Tokens;
 using System;
 using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
 using System.Linq;
 using System.Threading.Tasks;
+using TEAMModelOS.Models;
+using TEAMModelOS.SDK.Context.Configuration;
+using TEAMModelOS.SDK.DI;
+using TEAMModelOS.SDK.Models.Service;
 using VueCliMiddleware;
 
 namespace TEAMModeBI
 {
     public class Startup
     {
-        public Startup(IConfiguration configuration)
+        public IWebHostEnvironment environment { get; set; }
+        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
+        public Startup(IConfiguration configuration,IWebHostEnvironment env)
         {
             Configuration = configuration;
+            environment = env;
+            BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
         }
 
         public IConfiguration Configuration { get; }
@@ -25,6 +36,65 @@ namespace TEAMModeBI
         // This method gets called by the runtime. Use this method to add services to the container.
         public void ConfigureServices(IServiceCollection services)
         {
+            // true,默認情況下,聲明映射將以舊格式映射聲明名稱,以適應較早的SAML應用程序,RoleClaimType = 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role'
+            // false,RoleClaimType = 'roles'             
+            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
+            services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
+                .AddJwtBearer(options => //AzureADJwtBearer
+                {
+                    //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
+                    options.Authority = Configuration["Option:Authority"];
+                    options.Audience = Configuration["Option:Audience"];
+                    options.RequireHttpsMetadata = true;
+                    options.TokenValidationParameters = new TokenValidationParameters
+                    {
+                        RoleClaimType = "roles",
+                        ValidAudiences = new string[] { Configuration["Option:Audience"], $"api://{Configuration["Option:Audience"]}" }
+                    };
+                    options.Events = new JwtBearerEvents();
+                    //下列事件有需要紀錄則打開
+                    //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
+                    //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
+                    //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
+                    //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
+                    options.Events.OnTokenValidated = async context =>
+                    {
+                        if (!context.Principal.Claims.Any(x => x.Type.Equals("http://schemas.microsoft.com/identity/claims/scope")) //ClaimConstants.Scope
+                        && !context.Principal.Claims.Any(y => y.Type.Equals("roles"))) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
+                        {
+                            //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
+                            throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
+                        }
+                        await Task.FromResult(0);
+                    };
+                });
+            //設定跨域請求
+            services.AddCors(options =>
+            {
+                options.AddPolicy(MyAllowSpecificOrigins,
+                builder =>
+                {
+                    builder.WithOrigins("http://teammodelos-test.chinacloudsites.cn",
+                                        "https://www.teammodel.cn", "https://localhost:5001",
+                                        "http://localhost:5000")
+                                       
+                    .AllowAnyHeader()
+                    .AllowAnyMethod();
+                });
+            });
+            services.AddAzureStorage(Configuration.GetValue<string>("Azure:Storage:ConnectionString"));
+            services.AddAzureRedis(Configuration.GetValue<string>("Azure:Redis:ConnectionString"));
+            services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
+            services.AddAzureServiceBus(Configuration.GetValue<string>("Azure:ServiceBus:ConnectionString"));
+            services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
+            services.AddHttpClient();
+            services.AddHttpClient<DingDing>();
+            services.AddHttpClient<NotificationService>();
+            services.AddMemoryCache();
+            services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
+            //HttpContextAccessor,并用来访问HttpContext。(提供組件或非控制器服務存取HttpContext)
+            services.AddHttpContextAccessor();
+            services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
             services.AddControllers();
             services.AddSpaStaticFiles(configuration =>
             {
@@ -41,7 +111,14 @@ namespace TEAMModeBI
             }
 
             app.UseRouting();
+            //以下需要按照順序載入中間件  如果应用调用 UseStaticFiles,请将 UseStaticFiles 置于 UseRouting之前。
+            app.UseStaticFiles();
             app.UseSpaStaticFiles();
+            app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
+            app.UseHttpsRedirection(); //開發中暫時關掉
+            //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的
+            //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前
+            app.UseAuthentication();
             app.UseAuthorization();
 
             app.UseEndpoints(endpoints =>

+ 4 - 0
TEAMModeBI/TEAMModeBI.csproj

@@ -21,6 +21,10 @@
     <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
   </ItemGroup>
 
+  <ItemGroup>
+    <ProjectReference Include="..\TEAMModelOS.SDK\TEAMModelOS.SDK.csproj" />
+  </ItemGroup>
+
   <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
     <!-- Ensure Node.js is installed -->
     <Exec Command="node --version" ContinueOnError="true">

+ 49 - 3
TEAMModeBI/appsettings.Development.json

@@ -1,9 +1,55 @@
 {
   "Logging": {
     "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
+      "Default": "Debug",
+      "System": "Information",
+      "Microsoft": "Information"
+    }
+  },
+  "AllowedHosts": "*",
+  "Option": {
+    "Location": "China-Dep",
+    "LocationNum": "1",
+    "HostName": "localhost:5001",
+    "AllowedHosts": [ "localhost", "*.teammodel.cn", "*.teammodel.net", "*.habookaclass.biz", "test" ],
+    "Issuer": "www.teammodel.cn",
+    "JwtSecretKey": "fXO6ko/qyXeYrkecPeKdgXnuLXf9vMEtnBC9OB3s+aA=",
+    "Exp": 86400,
+    "IdTokenSalt": "8263692E2213497BB55E74792B7900B4",
+    "HttpTrigger": "https://teammodelosfunction-test.chinacloudsites.cn/api/"
+    //"HttpTrigger": "http://localhost:7071/api/"
+  },
+  "Azure": {
+    //
+    "Storage": {
+      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn"
+      //"ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelos;AccountKey=Dl04mfZ9hE9cdPVO1UtqTUQYN/kz/dD/p1nGvSq4tUu/4WhiKcNRVdY9tbe8620nPXo/RaXxs+1F9sVrWRo0bg==;EndpointSuffix=core.chinacloudapi.cn"
+    },
+    "Cosmos": {
+      "ConnectionString": "AccountEndpoint=https://cdhabookdep-free.documents.azure.cn:443/;AccountKey=JTUVk92Gjsx17L0xqxn0X4wX2thDPMKiw4daeTyV1HzPb6JmBeHdtFY1MF1jdctW1ofgzqkDMFOtcqS46by31A==;"
+      //"ConnectionString": "AccountEndpoint=https://teammodelos.documents.azure.cn:443/;AccountKey=clF73GwPECfP1lKZTCvs8gLMMyCZig1HODFbhDUsarsAURO7TcOjVz6ZFfPqr1HzYrfjCXpMuVD5TlEG5bFGGg==;"
+    },
+    "Redis": {
+      "ConnectionString": "106.12.23.251:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240"
+      //"ConnectionString": "CoreRedisCN.redis.cache.chinacloudapi.cn:6380,password=LyJWP1ORJdv+poXWofAF97lhCEQPg1wXWqvtzXGXQuE=,ssl=True,abortConnect=False"
+    },
+    "ServiceBus": {
+      "ConnectionString": "Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=",
+      "ActiveTask": "dep-active-task",
+      "NoticeTask": "dep-notice-task"
+    }
+  },
+  "HaBookAuth": {
+    "CoreId": {
+      "userinfo": "https://api2.teammodel.cn/Oauth2/GetUserInfos"
+    },
+    "CoreService": {
+      "clientID": "c7317f88-7cea-4e48-ac57-a16071f7b884",
+      "clientSecret": "kguxh:V.PLmxBdaI@jnrTrDSth]A3346",
+      "deviceinfo": "https://api2.teammodel.cn/oauth2/getdeviceinfos",
+      "sendnotification": "https://api2.teammodel.net/service/sendnotification",
+      "getnotification": "https://api2.teammodel.net/service/getnotification",
+      "delnotification": "https://api2.teammodel.net/service/delnotification"
     }
   }
 }

+ 6 - 0
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -33,4 +33,10 @@
     <PackageReference Include="Microsoft.Azure.Cosmos.Table" Version="2.0.0-preview" />
     <PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
   </ItemGroup>
+
+
+
+  <ItemGroup>
+    <Folder Include="Models\Cosmos\Bi\" />
+  </ItemGroup>
 </Project>