IndexController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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("bind-school")]
  36. public async Task<IActionResult> BindSchool(JsonNode json)
  37. {
  38. string id=$"{json["id"]}";
  39. string name= $"{json["name"]}";
  40. string picture = $"{json["picture"]}";
  41. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "schools.json");
  42. string schools = await System.IO.File.ReadAllTextAsync(filePath);
  43. return Ok();
  44. }
  45. [HttpPost("device")]
  46. public IActionResult Device(JsonElement json )
  47. {
  48. try
  49. {
  50. string ip= GetIP();
  51. json.TryGetProperty("fp", out JsonElement fp);
  52. var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
  53. int hybrid = 0;
  54. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  55. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  56. if (data!=null)
  57. {
  58. hybrid=1;
  59. msg="云端服务连接成功!";
  60. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = data["centerUrl"], region = data["region"],ip= data["ip"] , nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  61. }
  62. else {
  63. msg="云端服务未连接!";
  64. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = "", region = "局域网·内网", ip = ip, nowtime= DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. code=500;
  70. msg="服务端异常!";
  71. }
  72. return Ok(new { code, msg });
  73. }
  74. /**
  75. {
  76. "type":"sms",//qrcode二维码扫码登录:randomCode必传; sms 短信验证登录:randomCode必传,mobile必传
  77. "randomCode",
  78. "mobile":"1528377****"
  79. }
  80. **/
  81. /// <summary>
  82. /// 登录验证
  83. /// </summary>
  84. /// <param name="randomCode"></param>
  85. /// <returns></returns>
  86. [HttpPost("login-check")]
  87. public async Task<IActionResult> LoginCheck(JsonNode json)
  88. {
  89. try
  90. {
  91. var type = json["type"];
  92. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  93. if (!string.IsNullOrWhiteSpace($"{type}"))
  94. {
  95. TmdidImplicit? token = null;
  96. string x_auth_token = string.Empty;
  97. List<School>? schools = null;
  98. JsonNode? jsonNode = null;
  99. long time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  100. switch (true)
  101. {
  102. //跳过忽略,但是仍然要以访客身份登录
  103. case bool when $"{type}".Equals(ExamConstant.ScopeVisitor):
  104. {
  105. string id = $"{DateTimeOffset.Now.ToUnixTimeSeconds()}";
  106. string name = $"访客教师-{Random.Shared.Next(100, 999)}";
  107. x_auth_token = JwtAuthExtension.CreateAuthToken("www.teammodel.cn",id ,name,null
  108. ,ExamConstant.JwtSecretKey,ExamConstant.ScopeVisitor,8,null,new string[] { "visitor" }, expire: 1);
  109. // _memoryCache.Set($"Teacher:{id}", new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token });
  110. _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 });
  111. return Ok(new { code = 200,x_auth_token = x_auth_token });
  112. }
  113. case bool when $"{type}".Equals("qrcode"):
  114. {
  115. string randomCode = $"{json["randomCode"]}";
  116. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
  117. var response = await _httpClientFactory.CreateClient().GetAsync($"{CenterUrl}/hita/check-login?code={randomCode}");
  118. if (response.IsSuccessStatusCode)
  119. {
  120. string content = await response.Content.ReadAsStringAsync();
  121. if (!string.IsNullOrWhiteSpace(content))
  122. {
  123. jsonNode = content.ToObject<JsonNode>();
  124. }
  125. else
  126. {
  127. code=400;
  128. msg="随机码验证失败";
  129. }
  130. }
  131. else
  132. {
  133. code=400;
  134. msg="随机码验证错误";
  135. }
  136. break;
  137. }
  138. case bool when $"{type}".Equals("smspin"):
  139. {
  140. string pin_code = $"{json["pin_code"]}";
  141. string account = $"{json["account"]}";
  142. var response = await _httpClientFactory.CreateClient().PostAsJsonAsync($"{CenterUrl}/core/sendsms/check", new { pin_code, account });
  143. if (response.IsSuccessStatusCode)
  144. {
  145. string content = await response.Content.ReadAsStringAsync();
  146. if (!string.IsNullOrWhiteSpace(content))
  147. {
  148. jsonNode = content.ToObject<JsonNode>();
  149. }
  150. else
  151. {
  152. code=400;
  153. msg="短信验证返回结果为空";
  154. }
  155. }
  156. else
  157. {
  158. code=400;
  159. msg="短信验证错误";
  160. }
  161. break;
  162. }
  163. }
  164. if (jsonNode != null && $"{jsonNode["code"]}".Equals("200"))
  165. {
  166. token =jsonNode["implicit_token"]?.ToObject<TmdidImplicit>();
  167. x_auth_token = $"{jsonNode["x_auth_token"]}";
  168. schools =jsonNode["schools"]?.ToObject<List<School>>();
  169. var jwt = new JwtSecurityToken(token?.id_token);
  170. var id = jwt.Payload.Sub;
  171. jwt.Payload.TryGetValue("name", out object? name);
  172. jwt.Payload.TryGetValue("picture", out object? picture);
  173. //_memoryCache.Set($"Teacher:{id}", new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token });
  174. _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 });
  175. return Ok(new { code=200,/* implicit_token = token, schools = schools , */ x_auth_token = x_auth_token });
  176. }
  177. else
  178. {
  179. code=400;
  180. msg="验证失败";
  181. }
  182. }
  183. else
  184. {
  185. code=400;
  186. msg="参数错误";
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. code=500;
  192. msg="异常错误";
  193. }
  194. return Ok(new { code = code,msg });
  195. }
  196. /*
  197. */
  198. /// <summary>
  199. /// 登录模式初始化
  200. /// </summary>
  201. /// <returns></returns>
  202. [HttpPost("login-init")]
  203. public async Task<IActionResult> LoginInit(JsonNode json)
  204. {
  205. var type = json["type"];
  206. string qrcode = string.Empty;
  207. string randomCode = "";
  208. switch (true)
  209. {
  210. case bool when $"{type}".Equals("qrcode"):
  211. {
  212. //.NET Core使用SkiaSharp快速生成二维码 https://cloud.tencent.com/developer/article/2336486
  213. // 生成二维码图片
  214. Random random = new Random();
  215. randomCode = $"{random.Next(1000, 9999)}";
  216. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  217. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  218. var str= QRCodeHelper.GenerateQRCode(content, 300, 300,QRCodeHelper.logo);
  219. qrcode = $"data:image/png;base64,{str}";
  220. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  221. }
  222. case bool when $"{type}".Equals("xqrcode"):
  223. {
  224. // 生成二维码图片
  225. Random random = new Random();
  226. randomCode = $"{random.Next(1000, 9999)}";
  227. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  228. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  229. Bitmap qrCodeImage = QRCodeHelper.GetBitmap(content, 200, 200);
  230. using (MemoryStream stream = new MemoryStream())
  231. {
  232. qrCodeImage.Save(stream, ImageFormat.Png);
  233. byte[] data = stream.ToArray();
  234. qrcode=$"data:image/png;base64,{Convert.ToBase64String(data)}";
  235. }
  236. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  237. }
  238. case bool when $"{type}".Equals("smspin"):
  239. {
  240. int send = 0;
  241. if (!string.IsNullOrWhiteSpace($"{json["area"]}") && !string.IsNullOrWhiteSpace($"{json["to"]}"))
  242. {
  243. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  244. string url = $"{CenterUrl}/core/sendsms/pin";
  245. HttpResponseMessage message = await _httpClientFactory.CreateClient().PostAsJsonAsync(url, new { area=json["area"], to = json["to"], lang="zh-cn" });
  246. if (message.IsSuccessStatusCode)
  247. {
  248. string content = await message.Content.ReadAsStringAsync();
  249. JsonNode? jsonNode = content?.ToObject<JsonNode>();
  250. if (jsonNode!=null && int.TryParse($"{jsonNode["send"]}", out int s))
  251. {
  252. send = s;
  253. }
  254. }
  255. }
  256. return Ok(new { code = 200, send, type });
  257. }
  258. }
  259. return Ok(new { code = 400 });
  260. }
  261. }
  262. }