LoginController.cs 31 KB

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