IndexController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using IES.ExamServer.Models;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Caching.Memory;
  4. using System.Diagnostics;
  5. using System.Text.Json.Nodes;
  6. using System.Text.Json;
  7. using IES.ExamServer.Helper;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using IES.ExamServer.Services;
  10. using IES.ExamServer.DI;
  11. using IES.ExamServer.Helpers;
  12. using IES.ExamLibrary.Models;
  13. namespace IES.ExamServer.Controllers
  14. {
  15. [ApiController]
  16. [Route("index")]
  17. public class IndexController : BaseController
  18. {
  19. private readonly IConfiguration _configuration;
  20. private readonly IHttpClientFactory _httpClientFactory;
  21. private readonly IMemoryCache _memoryCache;
  22. private readonly ILogger<IndexController> _logger;
  23. private readonly CenterServiceConnectionService _connectionService;
  24. private readonly LiteDBFactory _liteDBFactory;
  25. private readonly IHostApplicationLifetime _hostApplicationLifetime;
  26. public IndexController(ILogger<IndexController> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory,
  27. IMemoryCache memoryCache,CenterServiceConnectionService connectionService, LiteDBFactory liteDBFactory, IHostApplicationLifetime hostApplicationLifetime)
  28. {
  29. _hostApplicationLifetime = hostApplicationLifetime;
  30. _logger = logger;
  31. _configuration=configuration;
  32. _httpClientFactory=httpClientFactory;
  33. _memoryCache=memoryCache;
  34. _connectionService=connectionService;
  35. _liteDBFactory=liteDBFactory;
  36. }
  37. /// <summary>
  38. /// 关闭当前进程的接口
  39. /// </summary>
  40. /// <returns></returns>
  41. [HttpGet("shutdown")]
  42. public IActionResult Shutdown(int delayMilliseconds = 200)
  43. {
  44. try
  45. {
  46. _ = Task.Run(async () =>
  47. {
  48. try
  49. {
  50. await Task.Delay(delayMilliseconds);
  51. _hostApplicationLifetime.StopApplication();
  52. }
  53. catch (Exception ex)
  54. {
  55. Console.Error.WriteLine($"Error during shutdown: {ex.Message}");
  56. }
  57. });
  58. return Ok("Shutdown process has been initiated.");
  59. }
  60. catch (Exception ex)
  61. {
  62. return StatusCode(500, $"Failed to initiate the shutdown process: {ex.Message}");
  63. }
  64. }
  65. [HttpGet("health")]
  66. public IActionResult Health()
  67. {
  68. return Ok(new { code=200});
  69. }
  70. [HttpPost("generate-certificate")]
  71. public async Task<IActionResult> GenerateCertificate(JsonNode json)
  72. {
  73. try {
  74. ServerDevice serverDevice = _memoryCache.Get<ServerDevice>(Constant._KeyServerDevice);
  75. if (serverDevice!=null && serverDevice.networks.IsNotEmpty())
  76. {
  77. string mac = $"{json["mac"]}";
  78. var network = serverDevice.networks.Find(x => mac.Equals(x.mac));
  79. if (network!=null)
  80. {
  81. string pathBat = Path.Combine(Directory.GetCurrentDirectory(), "Configs", "cer", "certificate.bat");
  82. string pathCer = Path.Combine(Directory.GetCurrentDirectory(), "Configs", "cer", "certificate.cer");
  83. string text = await System.IO.File.ReadAllTextAsync(pathBat);
  84. text = text.Replace("192.168.8.132", network.ip);
  85. string pathCertificateBat = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "certificate.bat");
  86. await System.IO.File.WriteAllTextAsync(pathCertificateBat, text);
  87. string pathCertificateCer = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "certificate.cer");
  88. System.IO.File.Copy(pathCer, pathCertificateCer);
  89. return Ok(new { code = 200, msg = "生成成功。", bat = "package/certificate.bat", cer = "package/certificate.cer" });
  90. }
  91. else
  92. {
  93. msg="未找到匹配的网卡设备。";
  94. }
  95. }
  96. else
  97. {
  98. msg="服务端设备未找到,或网卡设备不存在。";
  99. }
  100. } catch (Exception ex)
  101. {
  102. _logger.LogError($"生成证书和自定义域名映射脚本错误。{ex.Message},{ex.StackTrace}");
  103. msg=$"服务端错误,{ex.Message}";
  104. }
  105. return Ok(new { code = 400, msg = msg });
  106. }
  107. [HttpPost("list-schools")]
  108. public async Task<IActionResult> ListSchool(JsonNode json)
  109. {
  110. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "schools.json");
  111. string schoolText = await System.IO.File.ReadAllTextAsync(filePath);
  112. JsonNode? node = schoolText.ToObject<JsonNode>();
  113. return Ok(new {code =200, schools= node?["schools"] });
  114. }
  115. [HttpPost("bind-school")]
  116. public async Task<IActionResult> BindSchool(JsonNode json)
  117. {
  118. string id=$"{json["id"]}";
  119. string name= $"{json["name"]}";
  120. string fp = $"{json["fp"]}";
  121. if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(fp))
  122. {
  123. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "schools.json");
  124. string schoolText = await System.IO.File.ReadAllTextAsync(filePath);
  125. List<School>? schools = schoolText.ToObject<JsonNode>()?["schools"]?.ToObject<List<School>>();
  126. School? school = schools?.Find(x => id.Equals(x.id) && name.Equals(x.name));
  127. if (school!=null)
  128. {
  129. _liteDBFactory.GetLiteDatabase().GetCollection<School>().DeleteAll();
  130. _liteDBFactory.GetLiteDatabase().GetCollection<School>().Upsert(school);
  131. IEnumerable<School> schoolsDb = _liteDBFactory.GetLiteDatabase().GetCollection<School>().FindAll();
  132. School? schoolDb = schools?.FirstOrDefault();
  133. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  134. if (server!=null)
  135. {
  136. server.school = school;
  137. }
  138. string ip = GetIP();
  139. var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
  140. int hybrid = 0;
  141. _memoryCache.Set(Constant._KeyServerDevice, server);
  142. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  143. _memoryCache.TryGetValue(Constant._KeyServerDevice, out server);
  144. if (data!=null)
  145. {
  146. hybrid=1;
  147. msg="云端服务连接成功!";
  148. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = data["centerUrl"], region = data["region"], ip = data["ip"], nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  149. }
  150. else
  151. {
  152. msg="云端服务未连接!";
  153. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = "", region = "局域网·内网", ip = ip, nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  154. }
  155. }
  156. else
  157. {
  158. return Ok(new { code = 400, msg = "绑定失败!" });
  159. }
  160. }
  161. else {
  162. return Ok(new { code = 400, msg = "参数错误!" });
  163. }
  164. }
  165. [HttpPost("device")]
  166. public IActionResult Device(JsonElement json )
  167. {
  168. try
  169. {
  170. string ip= GetIP();
  171. json.TryGetProperty("fp", out JsonElement fp);
  172. var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
  173. int hybrid = 0, notify = 0 ;
  174. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  175. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  176. if (_connectionService.notifyIsConnected)
  177. {
  178. notify=1;
  179. }
  180. if (_connectionService.centerIsConnected)
  181. {
  182. hybrid=1;
  183. }
  184. msg="服务端检测成功!";
  185. return Ok(new { code = 200, msg, data = new {
  186. notify,
  187. hybrid,
  188. device,
  189. centerUrl = hybrid==1 ? _connectionService.centerUrl : "",
  190. notifyUrl = notify==1 ? _connectionService.notifyUrl : "",
  191. region = data?["region"],
  192. ip = data!=null ? data?["ip"] : ip,
  193. nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
  194. server
  195. } });
  196. }
  197. catch (Exception ex)
  198. {
  199. code=500;
  200. msg="服务端异常!";
  201. }
  202. return Ok(new { code, msg });
  203. }
  204. /**
  205. {
  206. "type":"sms",//qrcode二维码扫码登录:randomCode必传; sms 短信验证登录:randomCode必传,mobile必传
  207. "randomCode",
  208. "mobile":"1528377****"
  209. }
  210. **/
  211. /// <summary>
  212. /// 登录验证
  213. /// </summary>
  214. /// <param name="randomCode"></param>
  215. /// <returns></returns>
  216. [HttpPost("login-check")]
  217. public async Task<IActionResult> LoginCheck(JsonNode json)
  218. {
  219. try
  220. {
  221. var type = json["type"];
  222. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  223. if (!string.IsNullOrWhiteSpace($"{type}"))
  224. {
  225. TmdidImplicit? token = null;
  226. string x_auth_token = string.Empty;
  227. List<School>? schools = null;
  228. JsonNode? jsonNode = null;
  229. long time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  230. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  231. School? school = null;
  232. if (server!=null)
  233. {
  234. school = server.school;
  235. }
  236. switch (true)
  237. {
  238. //跳过忽略,但是仍然要以访客身份登录
  239. case bool when $"{type}".Equals(ExamConstant.ScopeVisitor):
  240. {
  241. string id = $"{DateTimeOffset.Now.ToUnixTimeSeconds()}";
  242. string name = $"{school?.name}教师-{Random.Shared.Next(100, 999)}";
  243. x_auth_token = JwtAuthExtension.CreateAuthToken("www.teammodel.cn",id ,name,picture: school?.picture
  244. , ExamConstant.JwtSecretKey,ExamConstant.ScopeVisitor,8,schoolID:school?.id,new string[] { "visitor" }, expire: 1);
  245. // _memoryCache.Set($"Teacher:{id}", new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token });
  246. _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().Upsert(new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token,loginTime=time });
  247. return Ok(new { code = 200,x_auth_token = x_auth_token });
  248. }
  249. case bool when $"{type}".Equals("qrcode"):
  250. {
  251. string randomCode = $"{json["randomCode"]}";
  252. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
  253. var rc= _memoryCache.Get<string>($"Login:ExamServer:{school?.id}:{randomCode}");
  254. if (!string.IsNullOrWhiteSpace(rc))
  255. {
  256. var response = await _httpClientFactory.CreateClient().GetAsync($"{CenterUrl}/core/qrcode/check?randomcode={randomCode}&school={school?.id}&client=ExamServer");
  257. if (response.IsSuccessStatusCode)
  258. {
  259. string content = await response.Content.ReadAsStringAsync();
  260. if (!string.IsNullOrWhiteSpace(content))
  261. {
  262. jsonNode = content.ToObject<JsonNode>();
  263. }
  264. else
  265. {
  266. code=400;
  267. msg="随机码验证失败";
  268. }
  269. }
  270. else
  271. {
  272. code=400;
  273. msg="随机码验证错误";
  274. }
  275. }
  276. else
  277. {
  278. code=400;
  279. msg="二维码过期";
  280. }
  281. break;
  282. }
  283. case bool when $"{type}".Equals("smspin"):
  284. {
  285. string pin_code = $"{json["pin_code"]}";
  286. string account = $"{json["account"]}";
  287. var response = await _httpClientFactory.CreateClient().PostAsJsonAsync($"{CenterUrl}/core/sendsms/check", new { pin_code, account,school=school?.id });
  288. if (response.IsSuccessStatusCode)
  289. {
  290. string content = await response.Content.ReadAsStringAsync();
  291. if (!string.IsNullOrWhiteSpace(content))
  292. {
  293. jsonNode = content.ToObject<JsonNode>();
  294. }
  295. else
  296. {
  297. code=400;
  298. msg="短信验证返回结果为空";
  299. }
  300. }
  301. else
  302. {
  303. code=400;
  304. msg="短信验证错误";
  305. }
  306. break;
  307. }
  308. }
  309. if (jsonNode != null && $"{jsonNode["code"]}".Equals("200"))
  310. {
  311. token =jsonNode["implicit_token"]?.ToObject<TmdidImplicit>();
  312. x_auth_token = $"{jsonNode["x_auth_token"]}";
  313. schools =jsonNode["schools"]?.ToObject<List<School>>();
  314. var jwt = new JwtSecurityToken(token?.id_token);
  315. var id = jwt.Payload.Sub;
  316. jwt.Payload.TryGetValue("name", out object? name);
  317. jwt.Payload.TryGetValue("picture", out object? picture);
  318. //_memoryCache.Set($"Teacher:{id}", new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token });
  319. _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().Upsert(new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token ,loginTime=time });
  320. return Ok(new { code=200,/* implicit_token = token, schools = schools , */ x_auth_token = x_auth_token });
  321. }
  322. else
  323. {
  324. code=400;
  325. msg="验证失败";
  326. }
  327. }
  328. else
  329. {
  330. code=400;
  331. msg="参数错误";
  332. }
  333. }
  334. catch (Exception ex)
  335. {
  336. code=500;
  337. msg="异常错误";
  338. }
  339. return Ok(new { code = code,msg });
  340. }
  341. /*
  342. */
  343. /// <summary>
  344. /// 登录模式初始化
  345. /// </summary>
  346. /// <returns></returns>
  347. [HttpPost("login-init")]
  348. public async Task<IActionResult> LoginInit(JsonNode json)
  349. {
  350. var type = json["type"];
  351. string qrcode = string.Empty;
  352. string randomcode = "";
  353. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  354. School? school = null;
  355. if (server != null)
  356. {
  357. school = server.school;
  358. }
  359. if (school != null)
  360. {
  361. switch (true)
  362. {
  363. case bool when $"{type}".Equals("qrcode"):
  364. {
  365. //.NET Core使用SkiaSharp快速生成二维码 https://cloud.tencent.com/developer/article/2336486
  366. // 生成二维码图片
  367. Random random = new Random();
  368. randomcode = $"{random.Next(1000, 9999)}";
  369. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  370. CenterUrl = CenterUrl.Equals("https://localhost:5001") ? "https://www.teammodel.cn" : CenterUrl;
  371. string content = $"{CenterUrl}/qrcodelogin?randomcode=Login:ExamServer:{school?.id}:{randomcode}&m=%E6%89%AB%E7%A0%81%E7%99%BB%E5%BD%95&o=1";
  372. var str = QRCodeHelper.GenerateQRCode(content, 300, 300, QRCodeHelper.logo);
  373. qrcode = $"data:image/png;base64,{str}";
  374. int ttl = 180;
  375. string key = $"Login:ExamServer:{school?.id}:{randomcode}";
  376. _memoryCache.Set(key, randomcode, TimeSpan.FromSeconds(ttl));
  377. var device =IndexService.GetDevice(HttpContext,_memoryCache);
  378. _memoryCache.Set($"device:{key}", device);
  379. try {
  380. if (_connectionService.notifyIsConnected && _connectionService.serverDevice!=null)
  381. {
  382. string url = $"{_connectionService.notifyUrl!}/third/ies/qrcode-login-register";
  383. //扫描登录,远端设备登记临时随机码
  384. await _httpClientFactory.CreateClient().PostAsJsonAsync(url,new { randomcode= key, deviceid = _connectionService .serverDevice.deviceId});
  385. }
  386. } catch (Exception e) {
  387. _logger.LogError($"{e.Message},{e.StackTrace}");
  388. }
  389. return Ok(new { ttl,code = 200, randomCode = randomcode, qrcode, type });
  390. }
  391. //case bool when $"{type}".Equals("xqrcode"):
  392. // {
  393. // // 生成二维码图片
  394. // Random random = new Random();
  395. // randomcode = $"{random.Next(1000, 9999)}";
  396. // string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  397. // CenterUrl = CenterUrl.Equals("https://localhost:5001") ? "https://www.teammodel.cn" : CenterUrl;
  398. // string content = $"{CenterUrl}/qrcodelogin?randomcode=Login:ExamServer:{school?.id}:{randomcode}&m=%E6%89%AB%E7%A0%81%E7%99%BB%E5%BD%95&o=1";
  399. // Bitmap qrCodeImage = QRCodeHelper.GetBitmap(content, 200, 200);
  400. // using (MemoryStream stream = new MemoryStream())
  401. // {
  402. // qrCodeImage.Save(stream, ImageFormat.Png);
  403. // byte[] data = stream.ToArray();
  404. // qrcode = $"data:image/png;base64,{Convert.ToBase64String(data)}";
  405. // }
  406. // int ttl = 60;
  407. // _memoryCache.Set($"Login:ExamServer:{school?.id}:{randomcode}", randomcode, TimeSpan.FromSeconds(ttl));
  408. // return Ok(new {ttl, code = 200, randomCode = randomcode, qrcode, type });
  409. // }
  410. case bool when $"{type}".Equals("smspin"):
  411. {
  412. int send = 0;
  413. if (!string.IsNullOrWhiteSpace($"{json["area"]}") && !string.IsNullOrWhiteSpace($"{json["to"]}"))
  414. {
  415. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  416. string url = $"{CenterUrl}/core/sendsms/pin";
  417. HttpResponseMessage message = await _httpClientFactory.CreateClient().PostAsJsonAsync(url, new { area = json["area"], to = json["to"], lang = "zh-cn" });
  418. if (message.IsSuccessStatusCode)
  419. {
  420. string content = await message.Content.ReadAsStringAsync();
  421. JsonNode? jsonNode = content?.ToObject<JsonNode>();
  422. if (jsonNode != null && int.TryParse($"{jsonNode["send"]}", out int s))
  423. {
  424. send = s;
  425. }
  426. }
  427. }
  428. return Ok(new { code = 200, send, type });
  429. }
  430. }
  431. }
  432. else if (school == null)
  433. {
  434. return Ok(new { code = 400,msg="未绑定学校" });
  435. }
  436. return Ok(new { code = 400 });
  437. }
  438. }
  439. }