LecturerController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using Hei.Captcha;
  2. using HiTeachCE.Context;
  3. using HiTeachCE.Extension;
  4. using HiTeachCE.Helpers;
  5. using HiTeachCE.Models;
  6. using HiTeachCE.Services;
  7. using IdentityModel;
  8. using Microsoft.AspNetCore.Authorization;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.Extensions.Configuration;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Linq.Expressions;
  15. using System.Security.Claims;
  16. using System.Text.Json;
  17. using System.Threading.Tasks;
  18. using TEAMModelOS.SDK.Context.Configuration;
  19. using TEAMModelOS.SDK.Context.Exception;
  20. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
  21. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
  22. using TEAMModelOS.SDK.Extension.JwtAuth.Models;
  23. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  24. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  25. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  26. namespace HiTeachCE.Controllers
  27. {
  28. [Route("api/[controller]")]
  29. [ApiController]
  30. public class LecturerController : BaseController
  31. {
  32. public static int smsTTL = 1 * 60;
  33. public static int ticketTTL = 1 * 24 * 60 * 60;
  34. public static int freeTTL = 7 * 24 * 60 * 60;
  35. public static int deviceTTL = 1 * 24 * 60 * 60;
  36. public static string freeOrg = "7f847a9f05224184a5d01ee69a6b00d6";
  37. public static string model_teach = "teach";
  38. public static string model_prepare = "prepare";
  39. private readonly LecturerService lecturerService;
  40. private readonly OrganizationService organizationService;
  41. private readonly MemberService memberService;
  42. private readonly ActivationCodeService activationCodeService;
  43. private readonly SecurityCodeHelper securityCode;
  44. public LecturerController(LecturerService lecturer, OrganizationService organization, MemberService member, ActivationCodeService activationCode, SecurityCodeHelper _securityCode) {
  45. lecturerService = lecturer;
  46. organizationService = organization;
  47. memberService = member;
  48. activationCodeService = activationCode;
  49. securityCode = _securityCode;
  50. }
  51. /// <summary>
  52. /// 获取知识
  53. /// </summary>
  54. /// <param name="request"></param>
  55. /// <returns></returns>
  56. [HttpGet("GetId")]
  57. public BaseJosnRPCResponse GetList()
  58. {
  59. // request.@params.TryAdd("PartitionKey", request.lang);
  60. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  61. List<Lecturer> data = lecturerService.GetList();
  62. return builder.Data(Guid.NewGuid()).build();
  63. }
  64. /// <summary>
  65. /// 获取知识
  66. /// </summary>
  67. /// <param name="request"></param>
  68. /// <returns></returns>
  69. [HttpPost("GetList")]
  70. [Authorize(Roles = "admin")]
  71. public BaseJosnRPCResponse GetList(JosnRPCRequest<Dictionary<string, object>> request)
  72. {
  73. // request.@params.TryAdd("PartitionKey", request.lang);
  74. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  75. List<Lecturer> data = lecturerService.GetList() ;
  76. return builder.Data(Guid.NewGuid()).build();
  77. }
  78. /// <summary>
  79. /// 获取知识
  80. /// </summary>
  81. /// <param name="request"></param>
  82. /// <returns></returns>
  83. [HttpPost("GetList1")]
  84. [Authorize(Policy = "admin")]
  85. public BaseJosnRPCResponse GetList1(JosnRPCRequest<Dictionary<string, object>> request)
  86. {
  87. // request.@params.TryAdd("PartitionKey", request.lang);
  88. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  89. List<Lecturer> data = lecturerService.GetList();
  90. return builder.Data(Guid.NewGuid()).build();
  91. }/// <summary>
  92. /// 获取知识
  93. /// </summary>
  94. /// <param name="request"></param>
  95. /// <returns></returns>
  96. [HttpPost("GetList2")]
  97. [Authorize]
  98. public BaseJosnRPCResponse GetList2(JosnRPCRequest<Dictionary<string, object>> request)
  99. {
  100. // request.@params.TryAdd("PartitionKey", request.lang);
  101. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  102. return builder.Data(Guid.NewGuid()).build();
  103. }
  104. /// <summary>
  105. /// 注册装置
  106. /// </summary>
  107. /// <param name="request"></param>
  108. /// <returns></returns>
  109. [HttpPost("regist")]
  110. [Authorize(Policy = "lecturer")]
  111. public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
  112. {
  113. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  114. string unionid = GetLoginUser(JwtClaimTypes.Id);
  115. /**
  116. "params": {
  117. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  118. "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
  119. }
  120. */
  121. if (request.@params.TryGetValue("deviceId", out string deviceId)&& request.@params.TryGetValue("orgCode", out string orgCode) && string.IsNullOrEmpty(unionid))
  122. {
  123. Dictionary<string,object> dict = ActivationValid(orgCode, unionid);
  124. if (dict.TryGetValue("flag", out object flag) && bool.Parse(flag.ToString()))
  125. {
  126. if (RedisHelper.HExists("device:" + deviceId, orgCode))
  127. {
  128. }
  129. else
  130. {
  131. RedisHelper.HSet("device:" + deviceId, orgCode, unionid);
  132. RedisHelper.Expire("device:" + deviceId, deviceTTL);
  133. }
  134. return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
  135. }
  136. else
  137. {
  138. throw new BizException("授权失败!", 2);
  139. }
  140. }
  141. else
  142. {
  143. throw new BizException("参数错误!", 2);
  144. }
  145. }
  146. /// <summary>
  147. /// 教学认证
  148. /// </summary>
  149. /// <param name="request"></param>
  150. /// <returns></returns>
  151. [HttpPost("auth")]
  152. [Authorize(Policy = "lecturer")]
  153. public BaseJosnRPCResponse Auth(JosnRPCRequest<object> request)
  154. {
  155. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  156. string unionid = GetLoginUser(JwtClaimTypes.Id);
  157. Expression<Func<Member, bool>> mlinq = null;
  158. mlinq = m => m.unionid == unionid;
  159. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  160. List<Member> members = memberService.GetList(mlinq);
  161. if (members.IsNotEmpty())
  162. {
  163. foreach (var code in members)
  164. {
  165. dict.Add(ActivationValid(code.orgCode, unionid));
  166. }
  167. }
  168. else
  169. {
  170. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  171. ///处理该机构是否激活人数达到上线
  172. Expression<Func<Member, bool>> limitlinq = null;
  173. limitlinq = m => m.orgCode == freeOrg && (m.expires > time || m.expires == -1) && m.status == 1;
  174. List<Member> countMembers = memberService.GetList(limitlinq);
  175. Expression<Func<ActivationCode, bool>> alinq = null;
  176. alinq = m => m.orgCode == freeOrg && m.status == 1;
  177. List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
  178. if (activationCodes.IsNotEmpty())
  179. {
  180. //判断组织机构人员是否已经达到最大激活数量
  181. if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
  182. {
  183. //throw new BizException(":HiTeachCE(测试)授权人数超过上限!", 2);
  184. }
  185. else
  186. {
  187. Member member = new Member
  188. {
  189. id = Guid.NewGuid().ToString(),
  190. orgCode = freeOrg,
  191. role = "lecturer",
  192. status = 1,
  193. expires = time + freeTTL,
  194. unionid = unionid
  195. };
  196. bool flag = memberService.Insert(member);
  197. if (flag)
  198. {
  199. dict.Add(ActivationValid(freeOrg, unionid));
  200. }
  201. else
  202. {
  203. //throw new BizException("无法加入:HiTeachCE(测试)!", 2);
  204. }
  205. }
  206. }
  207. else {
  208. }
  209. }
  210. return builder.Data(dict).build();
  211. }
  212. public Dictionary<string, object> ActivationValid(string orgCode,string unionid) {
  213. //调用ActivationCode
  214. Expression<Func<Organization, bool>> olinq = null;
  215. olinq = m => m.code == orgCode && m.status == 1;
  216. Organization org = organizationService.GetList(olinq).First();
  217. Dictionary<string, object> dict = new Dictionary<string, object>() { { "org" , new { orgCode="",name=org.name} },{ "flag",false} };
  218. //验证组织机构的激活码状态,时间,最大人数
  219. Expression<Func<ActivationCode, bool>> linq = null;
  220. linq = m => m.orgCode == org.code;
  221. List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
  222. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  223. if (activationCodes[0].expires > time || activationCodes[0].expires == -1)
  224. {
  225. int max = activationCodes[0].maximum;
  226. Expression<Func<Member, bool>> mlinq = null;
  227. mlinq = l => l.orgCode == org.code;
  228. List<Member> members = memberService.GetList(mlinq);
  229. if (members.Count >= max)
  230. {
  231. dict.Add("msg", "产品授权人数超过上限!");
  232. }
  233. else {
  234. if (members.Where(x => x.status == 1 && (x.expires > time || x.expires == -1)).Select(x => x.unionid).ToList().Contains(unionid))
  235. {
  236. dict["org"] = new { orgCode = org.code, name = org.name };
  237. dict.Add("flag", true);
  238. }
  239. else {
  240. dict.Add("msg", "组织机构未对该用户授权或已经过期!");
  241. }
  242. }
  243. }
  244. else {
  245. dict.Add("msg", "产品授权已经过期!");
  246. }
  247. return dict;
  248. }
  249. /// <summary>
  250. /// 登录
  251. /// </summary>
  252. /// <param name="request"></param>
  253. /// <returns></returns>
  254. [HttpPost("phoneLogin")]
  255. public async Task<BaseJosnRPCResponse> PhoneLogin(JosnRPCRequest<Dictionary<string, string>> request)
  256. {
  257. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  258. if (request.@params.TryGetValue("cellphone", out string cellphone) &&
  259. request.@params.TryGetValue("smsCode", out string smsCode)
  260. )
  261. {
  262. string ticket = ShaHashHelper.GetSHA1(cellphone + smsCode);
  263. if (RedisHelper.Exists("ticket:" + ticket))
  264. {
  265. Dictionary<string, object> dict = UserValid(cellphone);
  266. dict.Add("ticket", ticket);
  267. return builder.Data(dict).build();
  268. }
  269. if (RedisHelper.Exists(cellphone))
  270. {
  271. string[] vals = RedisHelper.HVals<string>(cellphone);
  272. if (vals != null && vals.Length > 0)
  273. {
  274. string resdata = await HttpClientHelper.Post(
  275. BaseConfigModel.Configuration["JPush:Valid"].Replace("{msg_id}", vals[0]),
  276. BaseConfigModel.Configuration["JPush:AppKey"],
  277. BaseConfigModel.Configuration["JPush:Secret"], new Dictionary<string, object> { { "code", smsCode } });
  278. JsonElement element = resdata.FromApiJson<JsonElement>();
  279. if (element.TryGetProperty("is_valid", out JsonElement json))
  280. {
  281. if (json.GetBoolean())
  282. {
  283. ///验证通过 验证信息存放在reids
  284. RedisHelper.HSet("ticket:" + ticket, cellphone, cellphone);
  285. RedisHelper.Expire("ticket:" + ticket, ticketTTL);
  286. Dictionary<string, object> dict = UserValid(cellphone);
  287. dict.Add("ticket", ticket);
  288. return builder.Data(dict).build();
  289. }
  290. else
  291. {
  292. throw new BizException("短信验证码过期!", 2);
  293. }
  294. }
  295. else
  296. {
  297. throw new BizException("短信验证码过期!", 2);
  298. }
  299. }
  300. else
  301. {
  302. throw new BizException("短信验证码过期!", 2);
  303. }
  304. }
  305. else
  306. {
  307. throw new BizException("短信验证码过期!", 2);
  308. }
  309. }
  310. else
  311. {
  312. throw new BizException("手机号、短信验证码未填写!", 2);
  313. }
  314. //如果验证通过则将验证信息缓存至redis 以防再次远程验证不通过
  315. //string uid = "";
  316. //List<Organization> organizations = GetOrgByUid(uid);
  317. //return builder.Data(organizations).build();
  318. }
  319. private Dictionary<string, object> UserValid(string cellphone)
  320. {
  321. Expression<Func<Lecturer, bool>> linq = null;
  322. linq = m => m.cellphone == cellphone;
  323. List<Lecturer> lecturers = lecturerService.GetList(linq);
  324. if (lecturers.IsNotEmpty())
  325. {
  326. var lecturer = lecturers[0];
  327. ClaimModel claimModel = new ClaimModel
  328. {
  329. Scope = "WebApp"
  330. };
  331. claimModel.Claims.Add(new Claim(JwtClaimTypes.Name, lecturer.username));
  332. claimModel.Claims.Add(new Claim(JwtClaimTypes.Id, lecturer.unionid));
  333. claimModel.Claims.Add(new Claim(JwtClaimTypes.PhoneNumber, lecturer.cellphone));
  334. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  335. string role = "admin,lecturer";
  336. if (RootUsers.Contains(lecturers[0].cellphone)) {
  337. role = "root," + role;
  338. }
  339. // claimModel.Claims.Add(new Claim(JwtClaimTypes.Role, role));
  340. // 可以将一个用户的多个角色全部赋予;
  341. claimModel.Claims.AddRange(role.Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
  342. // claimModel.Claims.Add(new Claim(JwtClaimTypes.ClientId, activationCodes[0].clientId));
  343. // claimModel.Claims.Add(new Claim("org", orgCode));
  344. JwtResponse jwtResponse = JwtHelper.IssueJWT(claimModel);
  345. return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse } };
  346. }
  347. else {
  348. //不存在用户则新增一个
  349. Random random = new Random();
  350. string seed = new string(Constant.az09);
  351. string pfx = "";
  352. for (int i = 0; i < 4; i++)
  353. {
  354. string c = seed.ToCharArray()[random.Next(0, seed.Length)] + "";
  355. seed.Replace(c, "");
  356. pfx = pfx + c;
  357. }
  358. return new Dictionary<string, object> {
  359. { "status",1},
  360. { "user",new Lecturer
  361. {
  362. id= Guid.NewGuid().ToString(),
  363. unionid= Guid.NewGuid().ToString("N"),
  364. username=cellphone+"手机用户",
  365. password="",
  366. account="hitmd-"+cellphone.Substring(cellphone.Length-4,4)+"#"+pfx,
  367. areaCode="86",
  368. registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
  369. status=1,
  370. setaccount=0,
  371. cellphone=cellphone
  372. }
  373. }
  374. };
  375. }
  376. }
  377. }
  378. }