InitController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. namespace IES.ExamServer.Controllers
  12. {
  13. [ApiController]
  14. [Route("init")]
  15. public class InitController : ControllerBase
  16. {
  17. private readonly IConfiguration _configuration;
  18. private readonly IHttpClientFactory _httpClientFactory;
  19. private readonly IMemoryCache _memoryCache;
  20. private readonly ILogger<InitController> _logger;
  21. public InitController(ILogger<InitController> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache)
  22. {
  23. _logger = logger;
  24. _configuration=configuration;
  25. _httpClientFactory=httpClientFactory;
  26. _memoryCache=memoryCache;
  27. }
  28. [HttpPost("device")]
  29. public async Task<IActionResult> Device()
  30. {
  31. int code = 0;
  32. string msg = string.Empty;
  33. try
  34. {
  35. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  36. if (data!=null)
  37. {
  38. return Ok(new { code = 200, msg = "云端服务连接成功!", data = data });
  39. }
  40. else
  41. {
  42. code=500;
  43. msg="云端服务未连接!";
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. code=500;
  49. msg="云端服务未连接!";
  50. }
  51. return Ok(new { code, msg });
  52. }
  53. /**
  54. {
  55. "type":"sms",//qrcode二维码扫码登录:randomCode必传; sms 短信验证登录:randomCode必传,mobile必传
  56. "randomCode",
  57. "mobile":"1528377****"
  58. }
  59. **/
  60. /// <summary>
  61. /// 登录验证
  62. /// </summary>
  63. /// <param name="randomCode"></param>
  64. /// <returns></returns>
  65. [HttpPost("login-check")]
  66. public async Task<IActionResult> LoginCheck(JsonNode json)
  67. {
  68. int code = 0;
  69. string msg = string.Empty;
  70. try
  71. {
  72. var type = json["type"];
  73. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  74. if (!string.IsNullOrWhiteSpace($"{type}"))
  75. {
  76. TmdidImplicit? token = null;
  77. string x_auth_token = string.Empty;
  78. List<School>? schools = null;
  79. JsonNode? jsonNode = null;
  80. switch (true)
  81. {
  82. case bool when $"{type}".Equals("qrcode"):
  83. {
  84. string randomCode = $"{json["randomCode"]}";
  85. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
  86. var response = await _httpClientFactory.CreateClient().GetAsync($"{CenterUrl}/hita/check-login?code={randomCode}");
  87. if (response.IsSuccessStatusCode)
  88. {
  89. string content = await response.Content.ReadAsStringAsync();
  90. if (!string.IsNullOrWhiteSpace(content))
  91. {
  92. jsonNode = JsonSerializer.Deserialize<JsonNode>(content);
  93. }
  94. else
  95. {
  96. code=400;
  97. msg="随机码验证失败";
  98. }
  99. }
  100. else
  101. {
  102. code=400;
  103. msg="随机码验证错误";
  104. }
  105. break;
  106. }
  107. case bool when $"{type}".Equals("smspin"):
  108. {
  109. string pin_code = $"{json["pin_code"]}";
  110. string account = $"{json["account"]}";
  111. var response = await _httpClientFactory.CreateClient().PostAsJsonAsync($"{CenterUrl}/core/sendsms/check", new { pin_code, account });
  112. if (response.IsSuccessStatusCode)
  113. {
  114. string content = await response.Content.ReadAsStringAsync();
  115. if (!string.IsNullOrWhiteSpace(content))
  116. {
  117. jsonNode = JsonSerializer.Deserialize<JsonNode>(content);
  118. }
  119. else
  120. {
  121. code=400;
  122. msg="短信验证返回结果为空";
  123. }
  124. }
  125. else
  126. {
  127. code=400;
  128. msg="短信验证错误";
  129. }
  130. break;
  131. }
  132. }
  133. if (jsonNode != null && $"{jsonNode["code"]}".Equals("200"))
  134. {
  135. token = JsonSerializer.Deserialize<TmdidImplicit>(jsonNode["implicit_token"]);
  136. x_auth_token = $"{jsonNode["x_auth_token"]}";
  137. schools = JsonSerializer.Deserialize<List<School>>(jsonNode["schools"]);
  138. var jwt = new JwtSecurityToken(token?.id_token);
  139. var id = jwt.Payload.Sub;
  140. jwt.Payload.TryGetValue("name", out object? name);
  141. jwt.Payload.TryGetValue("picture", out object? picture);
  142. _memoryCache.Set($"Teacher:{id}", new LoginTeacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token });
  143. return Ok(new { implicit_token = token, x_auth_token = x_auth_token, schools = schools });
  144. }
  145. else
  146. {
  147. code=400;
  148. msg="验证失败";
  149. }
  150. }
  151. else
  152. {
  153. code=400;
  154. msg="参数错误";
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. code=500;
  160. msg="异常错误";
  161. }
  162. return Ok(new { code = code });
  163. }
  164. /*
  165. */
  166. /// <summary>
  167. /// 登录模式初始化
  168. /// </summary>
  169. /// <returns></returns>
  170. [HttpPost("login-init")]
  171. public async Task<IActionResult> LoginInit(JsonNode json)
  172. {
  173. var type = json["type"];
  174. string qrcode = string.Empty;
  175. string randomCode = "";
  176. switch (true)
  177. {
  178. case bool when $"{type}".Equals("skiaqrcode"):
  179. {
  180. //.NET Core使用SkiaSharp快速生成二维码 https://cloud.tencent.com/developer/article/2336486
  181. // 生成二维码图片
  182. Random random = new Random();
  183. randomCode = $"{random.Next(1000, 9999)}";
  184. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  185. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  186. var str= QRCodeHelper.GenerateQRCode(content, 200, 200);
  187. qrcode = $"data:image/png;base64,{str}";
  188. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  189. }
  190. case bool when $"{type}".Equals("qrcode"):
  191. {
  192. // 生成二维码图片
  193. Random random = new Random();
  194. randomCode = $"{random.Next(1000, 9999)}";
  195. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  196. string content = $"{CenterUrl}/joinSchool?schoolCode=login:{randomCode}&m=%E7%99%BB%E5%BD%95&o=1";
  197. Bitmap qrCodeImage = QRCodeHelper.GetBitmap(content, 200, 200);
  198. using (MemoryStream stream = new MemoryStream())
  199. {
  200. qrCodeImage.Save(stream, ImageFormat.Png);
  201. byte[] data = stream.ToArray();
  202. qrcode=$"data:image/png;base64,{Convert.ToBase64String(data)}";
  203. }
  204. return Ok(new { code = 200, randomCode = randomCode, qrcode, type });
  205. }
  206. case bool when $"{type}".Equals("smspin"):
  207. {
  208. int send = 0;
  209. if (!string.IsNullOrWhiteSpace($"{json["area"]}") && !string.IsNullOrWhiteSpace($"{json["to"]}"))
  210. {
  211. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  212. string url = $"{CenterUrl}/core/sendsms/pin";
  213. HttpResponseMessage message = await _httpClientFactory.CreateClient().PostAsJsonAsync(url, new { });
  214. if (message.IsSuccessStatusCode)
  215. {
  216. string content = await message.Content.ReadAsStringAsync();
  217. JsonNode? jsonNode = JsonSerializer.Deserialize<JsonNode>(content);
  218. if (jsonNode!=null && int.TryParse($"{jsonNode["send"]}", out int s))
  219. {
  220. send = s;
  221. }
  222. }
  223. }
  224. return Ok(new { code = 200, send, type });
  225. }
  226. }
  227. return Ok(new { code = 400 });
  228. }
  229. }
  230. }