IndexController.cs 22 KB

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