IndexController.cs 20 KB

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