LoginController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. using HiTeachCE.Extension;
  2. using HiTeachCE.Helpers;
  3. using HiTeachCE.Models;
  4. using HiTeachCE.Services;
  5. using IdentityModel;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Options;
  9. using OpenXmlPowerTools;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Linq.Expressions;
  14. using System.Security.Claims;
  15. using System.Text.Json;
  16. using System.Threading.Tasks;
  17. using TEAMModelOS.SDK.Context.Configuration;
  18. using TEAMModelOS.SDK.Context.Exception;
  19. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
  20. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
  21. using TEAMModelOS.SDK.Extension.JwtAuth.Models;
  22. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  23. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  24. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  25. namespace HiTeachCE.Controllers
  26. {
  27. [Route("api/[controller]")]
  28. [ApiController]
  29. public class LoginController : BaseController
  30. {
  31. public static int smsTTL = 4 * 60;
  32. public static int ticketTTL = 10 * 60;
  33. public static int freeTTL = 7 * 24 * 60 * 60;
  34. public static int deviceTTL=1 * 24 * 60 * 60;
  35. public static string freeOrg = "7f847a9f05224184a5d01ee69a6b00d6";
  36. public static string model_teach = "teach";
  37. public static string model_prepare = "prepare";
  38. private readonly LecturerService lecturerService;
  39. private readonly OrganizationService organizationService;
  40. private readonly MemberService memberService;
  41. private readonly ActivationCodeService activationCodeService;
  42. public readonly IOptions<Extension.JwtSetting> options;
  43. public LoginController(LecturerService lecturer, OrganizationService organization, MemberService member, ActivationCodeService activationCode, IOptions<Extension.JwtSetting> _options)
  44. {
  45. lecturerService = lecturer;
  46. organizationService = organization;
  47. memberService = member;
  48. activationCodeService = activationCode;
  49. options = _options;
  50. }
  51. /// <summary>
  52. /// 注册装置
  53. /// </summary>
  54. /// <param name="request"></param>
  55. /// <returns></returns>
  56. [HttpPost("regist")]
  57. public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
  58. {
  59. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  60. List<string> ClientId = new List<string>() { "fb564dde14df423cafac2085936e3b96" };/// GetLoginUser(JwtClaimTypes.ClientId);
  61. /**
  62. "params": {
  63. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  64. "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
  65. }
  66. */
  67. if (request.@params.TryGetValue("deviceId", out string deviceId) && ClientId.IsNotEmpty())
  68. {
  69. if (RedisHelper.HExists("device:" + ClientId[0], deviceId))
  70. {
  71. }
  72. else
  73. {
  74. RedisHelper.HSet("device:" + ClientId[0], deviceId, null);
  75. RedisHelper.Expire("device:" + ClientId[0], deviceTTL);
  76. }
  77. return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
  78. }
  79. else {
  80. throw new BizException("参数错误", 2);
  81. }
  82. }
  83. /// <summary>
  84. /// 创建教室
  85. /// </summary>
  86. /// <param name="request"></param>
  87. /// <returns></returns>
  88. [HttpPost("createGroup")]
  89. public BaseJosnRPCResponse CreateGroup(JosnRPCRequest<Dictionary<string, string>> request)
  90. {
  91. /**
  92. "params": {
  93. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  94. "doBoundGroupNum": false,
  95. "extraInfo": {}
  96. }
  97. */
  98. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  99. List<string> ClientId = new List<string>() { "fb564dde14df423cafac2085936e3b96" };
  100. // GetLoginUser(JwtClaimTypes.ClientId);
  101. string groupNum = "";
  102. if (request.@params.TryGetValue("deviceId", out string deviceId) && ClientId.IsNotEmpty())
  103. {
  104. if (RedisHelper.HExists("device:" + ClientId[0], deviceId))
  105. {
  106. groupNum= RedisHelper.HGet<string>("device:" + ClientId[0], deviceId);
  107. if (string.IsNullOrEmpty(groupNum)) {
  108. do
  109. {
  110. groupNum = RandGroupNum();
  111. } while (RedisHelper.Exists("group:" + groupNum));
  112. RedisHelper.HSet("group:" + groupNum, deviceId, null);
  113. RedisHelper.Expire("group:" + groupNum, deviceTTL);
  114. RedisHelper.HSet("device:" + ClientId[0], deviceId, groupNum);
  115. }
  116. }
  117. else { throw new BizException("装置未注册", 2); }
  118. }
  119. else {
  120. throw new BizException("参数错误", 2);
  121. }
  122. return builder.Data(groupNum).build();
  123. }
  124. public string RandGroupNum() {
  125. Random random = new Random();
  126. String result = "";
  127. for (int i = 0; i < 6; i++)
  128. {
  129. result += random.Next(0,10);
  130. }
  131. return result;
  132. }
  133. /// <summary>
  134. /// 加入教室
  135. /// </summary>
  136. /// <param name="request"></param>
  137. /// <returns></returns>
  138. [HttpPost("joinGroup")]
  139. public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
  140. {
  141. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  142. Dictionary<string, object> dict = new Dictionary<string, object>();
  143. /**
  144. "params": {
  145. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  146. "groupNum": "818288"
  147. }
  148. */
  149. if (request.@params.TryGetValue("deviceId", out string deviceId) &&
  150. request.@params.TryGetValue("groupNum", out string groupNum)&&
  151. !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(groupNum)
  152. )
  153. {
  154. if (RedisHelper.Exists("group:" + groupNum))
  155. {
  156. dynamic groupMember = new {
  157. deviceId,
  158. name= "🌱菁華浮梦",
  159. unionid= "b180ca87fea84c908a688c005b3f487e",
  160. role= "lecturer",
  161. org= "7f847a9f05224184a5d01ee69a6b00d6",
  162. phone_number="15283771540"
  163. };
  164. Dictionary<string, string> connectInfo = new Dictionary<string, string>() {
  165. { "brokerHostName", "cdhabook.teammodel.cn" },
  166. { "brokerHostNameWSS", "wss://cdhabook.teammodel.cn/mqtt" },
  167. { "clientID", deviceId },
  168. //使用BCrypt加密
  169. { "password", "cdhabook.teammodel.cn" },
  170. { "username", "cdhabook.teammodel.cn/"+deviceId }
  171. };
  172. RedisHelper.HSet("group:" + groupNum, deviceId, groupMember) ;
  173. dict.Add("mqtt", new Dictionary<string,object>() { { "connectInfo", connectInfo },{ "groupMember", groupMember } });
  174. }
  175. else {
  176. throw new BizException("教室不存在", 2);
  177. }
  178. }
  179. else
  180. {
  181. throw new BizException("参数错误", 2);
  182. }
  183. return builder.Data(dict).build();
  184. }
  185. /// <summary>
  186. /// 认证
  187. /// </summary>
  188. /// <param name="request"></param>
  189. /// <returns></returns>
  190. [HttpPost("auth")]
  191. public BaseJosnRPCResponse auth(JosnRPCRequest<Dictionary<string, string>> request)
  192. {
  193. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  194. if (request.@params.TryGetValue("ticket", out string ticket) &&
  195. //上课模式 备课模式
  196. //request.@params.TryGetValue("model", out string model)&&
  197. // (model.Equals(model_teach )||model.Equals(model_prepare)) &&
  198. request.@params.TryGetValue("orgCode", out string orgCode)
  199. )
  200. {
  201. if (RedisHelper.Exists("ticket:" + ticket))
  202. {
  203. string[] vals = RedisHelper.HVals<string>("ticket:" + ticket);
  204. if (vals != null && vals.Length > 0)
  205. {
  206. string cellphone = vals[0];
  207. Expression<Func<Lecturer, bool>> linq = null;
  208. linq = m => m.cellphone == cellphone;
  209. List<Lecturer> lecturers = lecturerService.GetList(linq);
  210. if (lecturers.IsNotEmpty())
  211. {
  212. Expression<Func<Member, bool>> mlinq = null;
  213. mlinq = m => m.unionid == lecturers[0].unionid && m.orgCode == orgCode;
  214. List<Member> members = memberService.GetList(mlinq);
  215. if (members.IsNotEmpty())
  216. {
  217. if (members[0].expires == -1 || new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() < members[0].expires)
  218. {
  219. //永久用户及授权期内的用户
  220. //调用ActivationCode
  221. return builder.Data(ActivationValid(orgCode, lecturers[0])).build();
  222. }
  223. else
  224. {
  225. //授权过期
  226. throw new BizException("用户授权过期", 2);
  227. }
  228. }
  229. else
  230. {
  231. if (orgCode.Equals(freeOrg))
  232. {
  233. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  234. ///处理该机构是否激活人数达到上线
  235. Expression<Func<Member, bool>> limitlinq = null;
  236. limitlinq = m => m.orgCode == orgCode && (m.expires > time || m.expires == -1) && m.status == 1;
  237. List<Member> countMembers = memberService.GetList(limitlinq);
  238. Expression<Func<ActivationCode, bool>> alinq = null;
  239. alinq = m => m.orgCode == orgCode && m.status == 1;
  240. List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
  241. if (activationCodes.IsNotEmpty())
  242. {
  243. //判断组织机构人员是否已经达到最大激活数量
  244. if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
  245. {
  246. throw new BizException("产品授权人数超过上限!", 2);
  247. }
  248. else
  249. {
  250. Member member = new Member
  251. {
  252. id = Guid.NewGuid().ToString(),
  253. orgCode = orgCode,
  254. role = "lecturer",
  255. status = 1,
  256. expires = time + freeTTL,
  257. unionid = lecturers[0].unionid
  258. };
  259. bool flag = memberService.Insert(member);
  260. if (flag)
  261. {
  262. //调用ActivationCode
  263. return builder.Data(ActivationValid(orgCode, lecturers[0])).build();
  264. }
  265. else
  266. {
  267. throw new BizException("无法加入:HiTeachCE(测试)!", 2);
  268. }
  269. }
  270. }
  271. else
  272. {
  273. throw new BizException("产品未授权该组织或个人!", 2);
  274. }
  275. }
  276. else
  277. {
  278. throw new BizException("授权失败!", 2);
  279. }
  280. }
  281. }
  282. else
  283. {
  284. throw new BizException("登录用户不存在!", 2);
  285. }
  286. }
  287. else
  288. {
  289. throw new BizException("凭据过期!", 2);
  290. }
  291. }
  292. else
  293. {
  294. throw new BizException("凭据过期!", 2);
  295. }
  296. }
  297. else
  298. {
  299. throw new BizException("参数错误!", 2);
  300. }
  301. }
  302. public JwtResponse ActivationValid(string orgCode, Lecturer lecturer)
  303. {
  304. //验证组织机构的激活码状态,时间,最大人数
  305. Expression<Func<ActivationCode, bool>> linq = null;
  306. linq = m => m.orgCode == orgCode && m.status == 1;
  307. List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
  308. if (activationCodes.IsNotEmpty())
  309. {
  310. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  311. if (activationCodes[0].expires > time || activationCodes[0].expires == -1)
  312. {
  313. int max = activationCodes[0].maximum;
  314. Expression<Func<Member, bool>> mlinq = null;
  315. mlinq = l => l.orgCode == orgCode;
  316. List<Member> members = memberService.GetList(mlinq);
  317. if (members.Count >= max)
  318. {
  319. throw new BizException("产品授权人数超过上限!", 2);
  320. }
  321. else
  322. {
  323. // 未授权用户授权 生成JWT
  324. if (members.Where(x => x.status == 1 && (x.expires > time || x.expires == -1)).Select(x => x.unionid).ToList().Contains(lecturer.unionid))
  325. {
  326. string role = members.Where(x => x.unionid == lecturer.unionid && x.status == 1 && (x.expires > time || x.expires == -1)).First().role;
  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. claimModel.Claims.Add(new Claim(JwtClaimTypes.Role, role));
  335. claimModel.Claims.Add(new Claim(JwtClaimTypes.ClientId, activationCodes[0].clientId));
  336. claimModel.Claims.Add(new Claim("org", orgCode));
  337. JwtResponse jwtResponse = JwtHelper.IssueJWT(claimModel);
  338. return jwtResponse;
  339. }
  340. else
  341. {
  342. throw new BizException("组织机构未对该用户授权或已经过期!", 2);
  343. }
  344. }
  345. }
  346. else
  347. {
  348. throw new BizException("产品授权已经过期!", 2);
  349. }
  350. }
  351. else
  352. {
  353. throw new BizException("产品未授权该组织或个人!", 2);
  354. }
  355. }
  356. /// <summary>
  357. /// 登录
  358. /// </summary>
  359. /// <param name="request"></param>
  360. /// <returns></returns>
  361. [HttpPost("phoneLogin")]
  362. public async Task<BaseJosnRPCResponse> PhoneLogin(JosnRPCRequest<Dictionary<string, string>> request)
  363. {
  364. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  365. if (request.@params.TryGetValue("cellphone", out string cellphone) &&
  366. request.@params.TryGetValue("smsCode", out string smsCode)
  367. )
  368. {
  369. string ticket = ShaHashHelper.GetSHA1(cellphone + smsCode);
  370. if (RedisHelper.Exists("ticket:" + ticket))
  371. {
  372. Dictionary<string, object> dict = userValid(cellphone);
  373. dict.Add("ticket", ticket);
  374. return builder.Data(dict).build();
  375. }
  376. if (RedisHelper.Exists(cellphone))
  377. {
  378. string[] vals = RedisHelper.HVals<string>(cellphone);
  379. if (vals != null && vals.Length > 0)
  380. {
  381. string resdata = await HttpClientHelper.Post(
  382. BaseConfigModel.Configuration["JPush:Valid"].Replace("{msg_id}", vals[0]),
  383. BaseConfigModel.Configuration["JPush:AppKey"],
  384. BaseConfigModel.Configuration["JPush:Secret"], new Dictionary<string, object> { { "code", smsCode } });
  385. JsonElement element = resdata.FromApiJson<JsonElement>();
  386. if (element.TryGetProperty("is_valid", out JsonElement json))
  387. {
  388. if (json.GetBoolean())
  389. {
  390. ///验证通过 验证信息存放在reids
  391. RedisHelper.HSet("ticket:" + ticket, cellphone, cellphone);
  392. RedisHelper.Expire("ticket:" + ticket, ticketTTL);
  393. Dictionary<string, object> dict = userValid(cellphone);
  394. dict.Add("ticket", ticket);
  395. return builder.Data(dict).build();
  396. }
  397. else
  398. {
  399. throw new BizException("短信验证码过期!", 2);
  400. }
  401. }
  402. else
  403. {
  404. throw new BizException("短信验证码过期!", 2);
  405. }
  406. }
  407. else
  408. {
  409. throw new BizException("短信验证码过期!", 2);
  410. }
  411. }
  412. else
  413. {
  414. throw new BizException("短信验证码过期!", 2);
  415. }
  416. }
  417. else
  418. {
  419. throw new BizException("手机号、短信验证码未填写!", 2);
  420. }
  421. //如果验证通过则将验证信息缓存至redis 以防再次远程验证不通过
  422. //string uid = "";
  423. //List<Organization> organizations = GetOrgByUid(uid);
  424. //return builder.Data(organizations).build();
  425. }
  426. // [HttpPost("GetOrgByUid")]
  427. public List<Organization> GetOrgByUid(string uid)
  428. {
  429. Expression<Func<Member, bool>> mlinq = null;
  430. mlinq = m => m.unionid == uid && (m.expires > 0 || m.expires == -1) && m.status == 1;
  431. List<Member> members = memberService.GetList(mlinq);
  432. if (members.IsNotEmpty())
  433. {
  434. Expression<Func<Organization, bool>> olinq = null;
  435. olinq = o => members.Select(x => x.orgCode).ToList().Contains(o.code) && o.status == 1;
  436. List<Organization> organizations = organizationService.GetList(olinq);
  437. ///返回前端后倒计时10秒自动选择组织机构,以防再次验证的时候 reids过期
  438. return organizations;
  439. }
  440. else { return null; }
  441. }
  442. private Dictionary<string, object> userValid(string cellphone)
  443. {
  444. Expression<Func<Lecturer, bool>> linq = null;
  445. linq = m => m.cellphone == cellphone;
  446. List<Lecturer> lecturers = lecturerService.GetList(linq);
  447. if (lecturers.IsNotEmpty())
  448. {
  449. //用户存在则返回组织机构信息
  450. List<Organization> organizations = GetOrgByUid(lecturers[0].unionid);
  451. if (organizations.IsNotEmpty())
  452. {
  453. return new Dictionary<string, object> {
  454. { "status",2},
  455. { "org",organizations},
  456. };
  457. }
  458. else
  459. {
  460. //测试组织机构
  461. return new Dictionary<string, object> { { "status", 3 }, { "org", organizationService.GetByIds(new string[] { freeOrg }) } };
  462. }
  463. }
  464. else
  465. {
  466. //不存在用户则新增一个
  467. Random random = new Random();
  468. string seed = new string(Constant.az09);
  469. string pfx = "";
  470. for (int i = 0; i < 4; i++)
  471. {
  472. string c = seed.ToCharArray()[random.Next(0, seed.Length)] + "";
  473. seed.Replace(c, "");
  474. pfx = pfx + c;
  475. }
  476. return new Dictionary<string, object> {
  477. { "status",1},
  478. { "user",new Lecturer
  479. {
  480. id= Guid.NewGuid().ToString(),
  481. unionid= Guid.NewGuid().ToString("N"),
  482. username=cellphone+"手机用户",
  483. password="",
  484. account="hitmd-"+cellphone.Substring(cellphone.Length-4,4)+"#"+pfx,
  485. areaCode="86",
  486. registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
  487. status=1,
  488. setaccount=0
  489. }
  490. }
  491. };
  492. }
  493. }
  494. /// <summary>
  495. /// 初始化登录
  496. /// </summary>
  497. /// <param name="request"></param>
  498. /// <returns></returns>
  499. [HttpPost("init")]
  500. public BaseJosnRPCResponse Init(JosnRPCRequest<Dictionary<string, object>> request)
  501. {
  502. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  503. return builder.Data(Guid.NewGuid().ToString("N")).build();
  504. }
  505. /// <summary>
  506. /// 发送短信
  507. /// </summary>
  508. /// <param name="request"></param>
  509. /// <returns></returns>
  510. [HttpPost("sendSMS")]
  511. public async Task<BaseJosnRPCResponse> sendSMS(JosnRPCRequest<string> request)
  512. {
  513. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  514. string key = request.@params;
  515. if (!string.IsNullOrEmpty(key))
  516. {
  517. if (RedisHelper.Exists(key))
  518. {
  519. string[] vals = RedisHelper.HVals<string>(key);
  520. if (vals != null && vals.Length > 0)
  521. {
  522. Dictionary<string, object> data = new Dictionary<string, object>() { { "msgid", vals[0] }, { "repeat", true } };
  523. return builder.Data(data).build();
  524. }
  525. else
  526. {
  527. return builder.Data(await sendMsg(key)).build();
  528. }
  529. }
  530. else
  531. {
  532. return builder.Data(await sendMsg(key)).build();
  533. }
  534. }
  535. else
  536. {
  537. throw new BizException("请输入手机号!", 2);
  538. }
  539. }
  540. private static async Task<Dictionary<string, object>> sendMsg(string key)
  541. {
  542. Dictionary<string, object> data = new Dictionary<string, object>() { { "mobile", key }, { "temp_id", 1 }, { "sign_id", "" } };
  543. string resdata = await HttpClientHelper.Post(
  544. BaseConfigModel.Configuration["JPush:Push"],
  545. BaseConfigModel.Configuration["JPush:AppKey"],
  546. BaseConfigModel.Configuration["JPush:Secret"], data);
  547. JsonElement element = resdata.FromApiJson<JsonElement>();
  548. if (element.TryGetProperty("msg_id", out JsonElement msgid))
  549. {
  550. string msgidstr = msgid.GetString();
  551. RedisHelper.Del(new string[] { key });
  552. RedisHelper.HSet(key, key, msgidstr);
  553. RedisHelper.Expire(key, smsTTL);
  554. return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
  555. }
  556. else
  557. {
  558. throw new BizException("短信发送失败!", 2);
  559. }
  560. }
  561. }
  562. }