IndexController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 DataCenterConnectionService _connectionService;
  25. private readonly LiteDBFactory _liteDBFactory;
  26. public IndexController(ILogger<IndexController> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache,DataCenterConnectionService 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;
  102. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  103. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  104. if (data!=null)
  105. {
  106. hybrid=1;
  107. msg="云端服务连接成功!";
  108. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = data["centerUrl"], region = data["region"],ip= data["ip"] , nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  109. }
  110. else {
  111. msg="云端服务未连接!";
  112. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = "", region = "局域网·内网", ip = ip, nowtime= DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. code=500;
  118. msg="服务端异常!";
  119. }
  120. return Ok(new { code, msg });
  121. }
  122. /**
  123. {
  124. "type":"sms",//qrcode二维码扫码登录:randomCode必传; sms 短信验证登录:randomCode必传,mobile必传
  125. "randomCode",
  126. "mobile":"1528377****"
  127. }
  128. **/
  129. /// <summary>
  130. /// 登录验证
  131. /// </summary>
  132. /// <param name="randomCode"></param>
  133. /// <returns></returns>
  134. [HttpPost("login-check")]
  135. public async Task<IActionResult> LoginCheck(JsonNode json)
  136. {
  137. try
  138. {
  139. var type = json["type"];
  140. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  141. if (!string.IsNullOrWhiteSpace($"{type}"))
  142. {
  143. TmdidImplicit? token = null;
  144. string x_auth_token = string.Empty;
  145. List<School>? schools = null;
  146. JsonNode? jsonNode = null;
  147. long time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  148. switch (true)
  149. {
  150. //跳过忽略,但是仍然要以访客身份登录
  151. case bool when $"{type}".Equals(ExamConstant.ScopeVisitor):
  152. {
  153. string id = $"{DateTimeOffset.Now.ToUnixTimeSeconds()}";
  154. string name = $"访客教师-{Random.Shared.Next(100, 999)}";
  155. x_auth_token = JwtAuthExtension.CreateAuthToken("www.teammodel.cn",id ,name,null
  156. ,ExamConstant.JwtSecretKey,ExamConstant.ScopeVisitor,8,null,new string[] { "visitor" }, expire: 1);
  157. // _memoryCache.Set($"Teacher:{id}", new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token });
  158. _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 });
  159. return Ok(new { code = 200,x_auth_token = x_auth_token });
  160. }
  161. case bool when $"{type}".Equals("qrcode"):
  162. {
  163. string randomCode = $"{json["randomCode"]}";
  164. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
  165. var response = await _httpClientFactory.CreateClient().GetAsync($"{CenterUrl}/hita/check-login?code={randomCode}");
  166. if (response.IsSuccessStatusCode)
  167. {
  168. string content = await response.Content.ReadAsStringAsync();
  169. if (!string.IsNullOrWhiteSpace(content))
  170. {
  171. jsonNode = content.ToObject<JsonNode>();
  172. }
  173. else
  174. {
  175. code=400;
  176. msg="随机码验证失败";
  177. }
  178. }
  179. else
  180. {
  181. code=400;
  182. msg="随机码验证错误";
  183. }
  184. break;
  185. }
  186. case bool when $"{type}".Equals("smspin"):
  187. {
  188. string pin_code = $"{json["pin_code"]}";
  189. string account = $"{json["account"]}";
  190. var response = await _httpClientFactory.CreateClient().PostAsJsonAsync($"{CenterUrl}/core/sendsms/check", new { pin_code, account });
  191. if (response.IsSuccessStatusCode)
  192. {
  193. string content = await response.Content.ReadAsStringAsync();
  194. if (!string.IsNullOrWhiteSpace(content))
  195. {
  196. jsonNode = content.ToObject<JsonNode>();
  197. }
  198. else
  199. {
  200. code=400;
  201. msg="短信验证返回结果为空";
  202. }
  203. }
  204. else
  205. {
  206. code=400;
  207. msg="短信验证错误";
  208. }
  209. break;
  210. }
  211. }
  212. if (jsonNode != null && $"{jsonNode["code"]}".Equals("200"))
  213. {
  214. token =jsonNode["implicit_token"]?.ToObject<TmdidImplicit>();
  215. x_auth_token = $"{jsonNode["x_auth_token"]}";
  216. schools =jsonNode["schools"]?.ToObject<List<School>>();
  217. var jwt = new JwtSecurityToken(token?.id_token);
  218. var id = jwt.Payload.Sub;
  219. jwt.Payload.TryGetValue("name", out object? name);
  220. jwt.Payload.TryGetValue("picture", out object? picture);
  221. //_memoryCache.Set($"Teacher:{id}", new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token });
  222. _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 });
  223. return Ok(new { code=200,/* implicit_token = token, schools = schools , */ x_auth_token = x_auth_token });
  224. }
  225. else
  226. {
  227. code=400;
  228. msg="验证失败";
  229. }
  230. }
  231. else
  232. {
  233. code=400;
  234. msg="参数错误";
  235. }
  236. }
  237. catch (Exception ex)
  238. {
  239. code=500;
  240. msg="异常错误";
  241. }
  242. return Ok(new { code = code,msg });
  243. }
  244. /*
  245. */
  246. /// <summary>
  247. /// 登录模式初始化
  248. /// </summary>
  249. /// <returns></returns>
  250. [HttpPost("login-init")]
  251. public async Task<IActionResult> LoginInit(JsonNode json)
  252. {
  253. var type = json["type"];
  254. string qrcode = string.Empty;
  255. string randomCode = "";
  256. switch (true)
  257. {
  258. case bool when $"{type}".Equals("qrcode"):
  259. {
  260. //.NET Core使用SkiaSharp快速生成二维码 https://cloud.tencent.com/developer/article/2336486
  261. // 生成二维码图片
  262. Random random = new Random();
  263. randomCode = $"{random.Next(1000, 9999)}";
  264. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  265. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  266. var str= QRCodeHelper.GenerateQRCode(content, 300, 300,QRCodeHelper.logo);
  267. qrcode = $"data:image/png;base64,{str}";
  268. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  269. }
  270. case bool when $"{type}".Equals("xqrcode"):
  271. {
  272. // 生成二维码图片
  273. Random random = new Random();
  274. randomCode = $"{random.Next(1000, 9999)}";
  275. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  276. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  277. Bitmap qrCodeImage = QRCodeHelper.GetBitmap(content, 200, 200);
  278. using (MemoryStream stream = new MemoryStream())
  279. {
  280. qrCodeImage.Save(stream, ImageFormat.Png);
  281. byte[] data = stream.ToArray();
  282. qrcode=$"data:image/png;base64,{Convert.ToBase64String(data)}";
  283. }
  284. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  285. }
  286. case bool when $"{type}".Equals("smspin"):
  287. {
  288. int send = 0;
  289. if (!string.IsNullOrWhiteSpace($"{json["area"]}") && !string.IsNullOrWhiteSpace($"{json["to"]}"))
  290. {
  291. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  292. string url = $"{CenterUrl}/core/sendsms/pin";
  293. HttpResponseMessage message = await _httpClientFactory.CreateClient().PostAsJsonAsync(url, new { area=json["area"], to = json["to"], lang="zh-cn" });
  294. if (message.IsSuccessStatusCode)
  295. {
  296. string content = await message.Content.ReadAsStringAsync();
  297. JsonNode? jsonNode = content?.ToObject<JsonNode>();
  298. if (jsonNode!=null && int.TryParse($"{jsonNode["send"]}", out int s))
  299. {
  300. send = s;
  301. }
  302. }
  303. }
  304. return Ok(new { code = 200, send, type });
  305. }
  306. }
  307. return Ok(new { code = 400 });
  308. }
  309. }
  310. }