CrazyIter_Bin 4 kuukautta sitten
vanhempi
commit
dabd770db8

+ 2 - 2
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/ClientApp/public/signalr.html

@@ -38,13 +38,13 @@
     </div>
     <script>
         window.onload = function () {
-            const clientid = this.prompt('请输clientid')
+            const clientid = '9f4ad914254c028f0b724fe0800ee2ab-127.0.0.1';
             const data = {
                 clientid: clientid,
                 grant_type: 'check_file'
             }
             if (data.clientid) {
-                const url = `/signalr/exam?grant_type=${data.grant_type}&clientid=dedbdcf5545c6f83093883a63142687d-127.0.0.1`
+                const url = `/signalr/exam?grant_type=${data.grant_type}&clientid=${data.clientid}`
                 const connection = new signalR.HubConnectionBuilder()
                     .withUrl(url)
                     .configureLogging(signalR.LogLevel.Information)

+ 29 - 15
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/Controllers/IndexController.cs

@@ -100,19 +100,29 @@ namespace IES.ExamServer.Controllers
                 string ip=   GetIP();
                 json.TryGetProperty("fp", out JsonElement fp);
                 var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
-                int hybrid = 0;
+                int hybrid = 0, notify = 0 ;
                 _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
                 _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
-                if (data!=null)
+                if (_connectionService.notifyIsConnected)
+                { 
+                    notify=1;
+                }
+                if (_connectionService.centerIsConnected)
                 {
                     hybrid=1;
-                    msg="云端服务连接成功!";
-                    return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = data["centerUrl"], region = data["region"],ip= data["ip"] , nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
-                }
-                else {
-                    msg="云端服务未连接!";
-                    return Ok(new { code = 200, msg, data = new { hybrid, device,  centerUrl = "", region = "局域网·内网", ip = ip, nowtime= DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
                 }
+                msg="服务端检测成功!";
+                return Ok(new { code = 200, msg, data = new {
+                    notify,
+                    hybrid,
+                    device,
+                    centerUrl = hybrid==1 ? _connectionService.centerUrl : "",
+                    notifyUrl = notify==1 ? _connectionService.notifyUrl : "",
+                    region = data?["region"],
+                    ip = data!=null ? data?["ip"] : ip,
+                    nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
+                    server
+                } });
             }
             catch (Exception ex)
             {
@@ -273,7 +283,6 @@ namespace IES.ExamServer.Controllers
         [HttpPost("login-init")]
         public async Task<IActionResult> LoginInit(JsonNode json)
         {
-            
             var type = json["type"];
             string qrcode = string.Empty;
             string randomcode = "";
@@ -300,16 +309,21 @@ namespace IES.ExamServer.Controllers
                             var str = QRCodeHelper.GenerateQRCode(content, 300, 300, QRCodeHelper.logo);
                             qrcode = $"data:image/png;base64,{str}";
                             int ttl = 60;
-                            _memoryCache.Set($"Login:ExamServer:{school?.id}:{randomcode}", randomcode, TimeSpan.FromSeconds(ttl));
+                            string  key = $"Login:ExamServer:{school?.id}:{randomcode}";
+                            _memoryCache.Set(key, randomcode, TimeSpan.FromSeconds(ttl));
                             var device =IndexService.GetDevice(HttpContext,_memoryCache);
-                            _memoryCache.Set($"device:Login:ExamServer:{school?.id}:{randomcode}", device);
+
+                            _memoryCache.Set($"device:{key}", device);
                             try {
-                                string? NotifyUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
-                                if (_connectionService.notifyIsConnected) 
+                                if (_connectionService.notifyIsConnected && _connectionService.serverDevice!=null) 
                                 {
-                                    
+                                    string url = $"{_connectionService.notifyUrl!}/third/ies/qrcode-login-register";
+                                    //扫描登录,远端设备登记临时随机码
+                                    await _httpClientFactory.CreateClient().PostAsJsonAsync(url,new { randomcode= key, deviceid = _connectionService .serverDevice.deviceId});
                                 }
-                            } catch (Exception e) { }
+                            } catch (Exception e) {
+                                _logger.LogError($"{e.Message},{e.StackTrace}");
+                            }
                             return Ok(new { ttl,code = 200, randomCode = randomcode, qrcode, type });
                         }
                     case bool when $"{type}".Equals("xqrcode"):

+ 4 - 1
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/DI/CenterServiceConnectionService.cs

@@ -1,4 +1,6 @@
-namespace IES.ExamServer.DI
+using IES.ExamServer.Models;
+
+namespace IES.ExamServer.DI
 {
     public class CenterServiceConnectionService
     {
@@ -6,6 +8,7 @@
         private bool _notifyIsConnected;
         public string? centerUrl { get; set; }
         public string? notifyUrl { get; set; }
+        public ServerDevice? serverDevice {  get; set; }
         public bool notifyIsConnected
         {
             get { return string.IsNullOrWhiteSpace(notifyUrl) ? false : _notifyIsConnected; }

+ 3 - 0
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/DI/ServiceInitializer.cs

@@ -122,6 +122,9 @@ namespace IES.ExamServer.DI
             School? school = schools?.FirstOrDefault();
             serverDevice.school = school;
             _cache.Set(Constant._KeyServerDevice, serverDevice);
+           
+            _liteDBFactory.GetLiteDatabase().GetCollection<ServerDevice>().Upsert(serverDevice);
+            _connectionService.serverDevice = serverDevice;
             _lifetime.ApplicationStarted.Register(() =>
             {
                var serverDevice=  _cache.Get<ServerDevice>(Constant._KeyServerDevice);

+ 1 - 1
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/DI/SignalRCloudClientHub.cs

@@ -70,7 +70,7 @@ namespace IES.ExamServer.DI
                             deviceId=_memoryCache.Get<string>($"device:{randomcode}");
                         }
                         await  _signalRExamServerHub.SendMessage(_memoryCache,_logger, deviceId, Constant._Message_grant_type_ies_qrcode_login,
-                          new MessageContent {dataId=deviceId,dataName="",messageType =Constant._Message_type_message, status=1,content=$"{message?.ToJsonString()}"});
+                          new MessageContent {dataId=deviceId,dataName="",messageType =Constant._Message_type_message, status=1,content=$"{nodeData?.ToJsonString()}"});
                     }
                     else
                     {

+ 1 - 1
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/DI/SignalRHost/SignalRExamServerHub.cs

@@ -40,7 +40,7 @@ namespace IES.ExamServer.DI.SignalRHost
                 {
                     switch (true)
                     {
-                        case bool when grant_type.Equals(Constant._Message_grant_type_check_file):
+                        case bool when grant_type.Equals(Constant._Message_grant_type_ies_qrcode_login):
                             {
                                 await hubContext.Clients.Client(signalRClient.connid!).SendAsync("ReceiveMessage", messageBody);
                                 code=200;

+ 2 - 0
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/Helpers/Constant.cs

@@ -16,6 +16,8 @@ namespace IES.ExamServer.Helper
         public static readonly string _X_Auth_AuthToken = "X-Auth-AuthToken";
         public static readonly string _Message_grant_type_check_file = "check_file";
         public static readonly string _Message_grant_type_ies_qrcode_login = "ies_qrcode_login";
+        public static readonly string _Message_grant_type_download_file = "download_file";
+        public static readonly string _Message_grant_type_upload_data = "upload_data";
         public static readonly string _Message_type_message = "message";
         public static readonly string _Message_type_check = "check";
         public static readonly string _Message_type_download = "download";

+ 1 - 0
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/Models/ServerDevice.cs

@@ -5,6 +5,7 @@ namespace IES.ExamServer.Models
    
     public class ServerDevice
     {
+        public string? id { get; set; }
         public School? school { get; set; }
         /// <summary>
         /// 设备id

+ 8 - 3
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/Services/IndexService.cs

@@ -276,6 +276,7 @@ namespace IES.ExamServer.Services
             //}
             string hashData = ShaHashHelper.GetSHA1($"{device.name}-{device.remote}-{string.Join(",", device.uris.Select(x => $"{x.port}-{x.protocol}"))}-{device.os}-{string.Join(",", device.networks.Select(x => $"{x.mac}-{x.ip}"))}");
             device.deviceId=hashData;
+            device.id= hashData;
             return device;
         }
 
@@ -304,7 +305,11 @@ namespace IES.ExamServer.Services
                         var fingerprint = ck.Value.Split("-");
                         if (fingerprint.Length == 2 && IP.Equals(fingerprint[1]))
                         {
-                            _memoryCache.TryGetValue<string>($"device:{fingerprint}:{IP}", out  device);
+                            if (!_memoryCache.TryGetValue<string>($"device:{fingerprint[0]}:{IP}", out device)) 
+                            {
+                                _memoryCache.Set($"device:{fingerprint[0]}:{IP}", $"{fingerprint[0]}-{IP}");
+                                device = $"{fingerprint[0]}-{IP}";
+                            }
                             
                         }
                     }
@@ -354,11 +359,11 @@ namespace IES.ExamServer.Services
                             if (ck.Value.Equals(device))
                             {
                                 //redis如果存在则
-                                _memoryCache.TryGetValue<JsonNode>($"device:{fingerprint}:{IP}", out JsonNode device_exist);
+                                _memoryCache.TryGetValue<string>($"device:{fingerprint}:{IP}", out string device_exist);
                                 // 返回的则应该是ck.Value=exist_device_exist的数据
                                 if (device_exist!=null)
                                 {
-                                    if (!string.IsNullOrWhiteSpace($"{device_exist["device"]}"))
+                                    if (!string.IsNullOrWhiteSpace($"{device_exist}"))
                                     {
                                         //0是代表指纹和IP匹配,正常返回的
                                         status = 1;

+ 25 - 14
TEAMModelOS/Controllers/System/CoreController.cs

@@ -48,6 +48,7 @@ using TEAMModelOS.Services;
 using static TEAMModelOS.Controllers.Client.HiTAControlller;
 using DocumentFormat.OpenXml.Office2010.Excel;
 using System.Net.Http.Json;
+using System.ServiceModel.Channels;
 
 namespace TEAMModelOS.Controllers
 {
@@ -422,20 +423,20 @@ namespace TEAMModelOS.Controllers
         [ProducesDefaultResponseType]
         [HttpPost("qrcode/login")]
         //[Authorize(Roles = "HiTA")]
-        public async Task<IActionResult> SchoolJoin(QRCodeLoginCheck join)
+        public async Task<IActionResult> QRCodeLogin(QRCodeLoginCheck join)
         {
             try
             {
-                Dictionary<string, object> dict = new Dictionary<string, object>();
-                Dictionary<string, object> qure = new Dictionary<string, object>();
-                foreach (var a in HttpContext.Request.Query)
-                {
-                    qure.Add(a.Key, a.Value);
-                }
-                foreach (var a in HttpContext.Request.Headers)
-                {
-                    dict.Add(a.Key, a.Value);
-                }
+                //Dictionary<string, object> dict = new Dictionary<string, object>();
+                //Dictionary<string, object> qure = new Dictionary<string, object>();
+                //foreach (var a in HttpContext.Request.Query)
+                //{
+                //    qure.Add(a.Key, a.Value);
+                //}
+                //foreach (var a in HttpContext.Request.Headers)
+                //{
+                //    dict.Add(a.Key, a.Value);
+                //}
                 //await _dingDing.SendBotMsg(join.ToJsonString()+ dict.ToJsonString(), GroupNames.成都开发測試群組);
 
                 if (!string.IsNullOrWhiteSpace(join.id_token) && !string.IsNullOrWhiteSpace(join.randomcode) && join.randomcode.StartsWith("Login:"))
@@ -443,10 +444,20 @@ namespace TEAMModelOS.Controllers
                     var jwt = new JwtSecurityToken(join.id_token);
                     //await _dingDing.SendBotMsg(join.ToJsonString(), GroupNames.成都开发測試群組);
                     var id = jwt.Payload.Sub;
-                    await _azureRedis.GetRedisClient(8).StringSetAsync($"HiTA:{join.randomcode}", id, expiry: new TimeSpan(0, 0, 30));
+                    jwt.Payload.TryGetValue("name", out object name);
+                    jwt.Payload.TryGetValue("picture", out object picture);
+                    jwt.Payload.TryGetValue("lang", out object _jwtlang);
+                    await _azureRedis.GetRedisClient(8).StringSetAsync($"HiTA:{join.randomcode}", id, expiry: new TimeSpan(0, 5, 0));
                     try {
-                        await _httpClientFactory.CreateClient().PostAsJsonAsync($"https://www.winteach.cn/third/ies/qrcode-login-notify", new { randomcode = join.randomcode,tmdid=id});
-                    } catch (Exception ex) { }
+                        var data=   new { randomcode = join.randomcode, tmdid = id,tmdname= $"{name}", picture= $"{picture}",lang= $"{_jwtlang}", dingding = "1" };
+                        if (join.randomcode.Contains("ExamServer")) 
+                        {
+                            await _httpClientFactory.CreateClient().PostAsJsonAsync($"https://www.winteach.cn/third/ies/qrcode-login-notify", data);
+                        }
+                       // await _dingDing.SendBotMsg($"扫码登录转发通知{join.ToJsonString()},{data.ToJsonString()}", GroupNames.成都开发測試群組);
+                    } catch (Exception ex) {
+                       await _dingDing.SendBotMsg($"处理钉钉异常信息{ex.StackTrace},{ex.Message}", GroupNames.成都开发測試群組);
+                    }
                     return Ok(new { msg = "关闭弹窗以获取登录信息" ,code=200});
                 }
                 else { return Ok(new { code = 400, msg = $"参数错误{join.ToJsonString()}" }); }