LoginController.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 = 4 * 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 = Constant.Role_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!=null && 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(Policy = Constant.Role_Lecturer)]
  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(Policy = Constant.Role_LecturerLearner)]
  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("auth")]
  244. [Authorize(Policy = Constant.Role_Lecturer)]
  245. public BaseJosnRPCResponse Auth(JosnRPCRequest<object> request)
  246. {
  247. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  248. string unionid = GetLoginUser(JwtClaimTypes.Id);
  249. string phoneNumber = GetLoginUser(JwtClaimTypes.PhoneNumber);
  250. Expression<Func<Member, bool>> mlinq = null;
  251. mlinq = m => m.unionid == unionid;
  252. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  253. List<Member> members = memberService.GetList(mlinq);
  254. if (members.IsNotEmpty())
  255. {
  256. foreach (var code in members)
  257. {
  258. var dt = ActivationValid(code.orgCode, unionid);
  259. if (dt!=null) {
  260. dict.Add(dt);
  261. }
  262. }
  263. }
  264. else
  265. {
  266. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  267. ///处理该机构是否激活人数达到上线
  268. Expression<Func<Member, bool>> limitlinq = null;
  269. limitlinq = m => m.orgCode == freeOrg && m.status == 1;
  270. List<Member> countMembers = memberService.GetList(limitlinq);
  271. Expression<Func<ActivationCode, bool>> alinq = null;
  272. alinq = m => m.orgCode == freeOrg && m.status == 1;
  273. List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
  274. if (activationCodes.IsNotEmpty())
  275. {
  276. //判断组织机构人员是否已经达到最大激活数量
  277. if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
  278. {
  279. //throw new BizException(":HiTeachCE(测试)授权人数超过上限!", 2);
  280. }
  281. else
  282. {
  283. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  284. string role = "admin,lecturer";
  285. if (RootUsers.Contains(phoneNumber)) {
  286. role = "root," + role;
  287. }
  288. Member member = new Member
  289. {
  290. id = Guid.NewGuid().ToString(),
  291. orgCode = freeOrg,
  292. admin = 0,
  293. status = 1,
  294. // expires = time + freeTTL,
  295. unionid = unionid,
  296. createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
  297. };
  298. bool flag = memberService.Insert(member);
  299. if (flag)
  300. { var dt = ActivationValid(freeOrg, unionid);
  301. if (dt != null) {
  302. dict.Add(dt);
  303. }
  304. }
  305. else
  306. {
  307. //throw new BizException("无法加入:HiTeachCE(测试)!", 2);
  308. }
  309. }
  310. }
  311. else
  312. {
  313. }
  314. }
  315. return builder.Data(dict).build();
  316. }
  317. public Dictionary<string, object> ActivationValid(string orgCode, string unionid)
  318. {
  319. //调用ActivationCode
  320. Expression<Func<Organization, bool>> olinq = null;
  321. olinq = m => m.code == orgCode;
  322. Organization org = organizationService.GetList(olinq).FirstOrDefault();
  323. if (org != null) {
  324. Dictionary<string, object> dict = new Dictionary<string, object>() { { "org", new { orgCode = "", name = org.name } }, { "flag", false } };
  325. if (org.status != 1)
  326. {
  327. dict.Add("msg", "组织机构被禁用!");
  328. }
  329. else {
  330. //验证组织机构的激活码状态,时间,最大人数
  331. Expression<Func<ActivationCode, bool>> linq = null;
  332. linq = m => m.orgCode == org.code;
  333. List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
  334. if (activationCodes.IsNotEmpty())
  335. {
  336. if (activationCodes[0].status == 1)
  337. {
  338. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  339. if (activationCodes[0].expires > time)
  340. {
  341. int max = activationCodes[0].maximum;
  342. Expression<Func<Member, bool>> mlinq = null;
  343. mlinq = l => l.orgCode == org.code;
  344. List<Member> members = memberService.GetList(mlinq);
  345. if (members.Count > max)
  346. {
  347. dict.Add("msg", "产品授权人数超过上限!");
  348. }
  349. else
  350. {
  351. if (members.Where(x => x.status == 1).Select(x => x.unionid).ToList().Contains(unionid))
  352. {
  353. dict["org"] = new { orgCode = org.code, name = org.name };
  354. dict["flag"] = true;
  355. }
  356. else
  357. {
  358. dict.Add("msg", "组织机构未对该用户授权!");
  359. }
  360. }
  361. }
  362. else
  363. {
  364. dict.Add("msg", "产品授权已经过期!");
  365. }
  366. }
  367. else {
  368. dict.Add("msg", "组织机构授权状态被禁用!");
  369. }
  370. }
  371. else {
  372. dict.Add("msg", "组织机构没有授权信息!");
  373. }
  374. }
  375. return dict;
  376. }
  377. return null ;
  378. }
  379. /// <summary>
  380. /// 登录
  381. /// </summary>
  382. /// <param name="request"></param>
  383. /// <returns></returns>
  384. [HttpPost("phoneLogin")]
  385. public async Task<BaseJosnRPCResponse> PhoneLogin(JosnRPCRequest<Dictionary<string, string>> request)
  386. {
  387. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  388. if (request.@params.TryGetValue("cellphone", out string cellphone) &&
  389. request.@params.TryGetValue("smsCode", out string smsCode)
  390. )
  391. {
  392. string ticket = ShaHashHelper.GetSHA1(cellphone + smsCode);
  393. if (RedisHelper.Exists("ticket:" + ticket))
  394. {
  395. Dictionary<string, object> dict = UserValid(cellphone);
  396. dict.Add("ticket", ticket);
  397. return builder.Data(dict).build();
  398. }
  399. if (RedisHelper.Exists(cellphone))
  400. {
  401. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  402. if (RootUsers.Contains(cellphone) && smsCode.Equals("000000"))
  403. {
  404. ///验证通过 验证信息存放在reids
  405. RedisHelper.HSet("ticket:" + ticket, cellphone, cellphone);
  406. RedisHelper.Expire("ticket:" + ticket, ticketTTL);
  407. Dictionary<string, object> dict = UserValid(cellphone);
  408. dict.Add("ticket", ticket);
  409. return builder.Data(dict).build();
  410. }
  411. else {
  412. string[] vals = RedisHelper.HVals<string>(cellphone);
  413. if (vals != null && vals.Length > 0)
  414. {
  415. string resdata = await HttpClientHelper.Post(
  416. BaseConfigModel.Configuration["JPush:Valid"].Replace("{msg_id}", vals[0]),
  417. BaseConfigModel.Configuration["JPush:AppKey"],
  418. BaseConfigModel.Configuration["JPush:Secret"], new Dictionary<string, object> { { "code", smsCode } });
  419. JsonElement element = resdata.FromApiJson<JsonElement>();
  420. if (element.TryGetProperty("is_valid", out JsonElement json))
  421. {
  422. if (json.GetBoolean())
  423. {
  424. ///验证通过 验证信息存放在reids
  425. RedisHelper.HSet("ticket:" + ticket, cellphone, cellphone);
  426. RedisHelper.Expire("ticket:" + ticket, ticketTTL);
  427. Dictionary<string, object> dict = UserValid(cellphone);
  428. dict.Add("ticket", ticket);
  429. return builder.Data(dict).build();
  430. }
  431. else
  432. {
  433. throw new BizException("短信验证码过期!", 2);
  434. }
  435. }
  436. else
  437. {
  438. throw new BizException("短信验证码过期!", 2);
  439. }
  440. }
  441. else
  442. {
  443. throw new BizException("短信验证码过期!", 2);
  444. }
  445. }
  446. }
  447. else
  448. {
  449. throw new BizException("短信验证码过期!", 2);
  450. }
  451. }
  452. else
  453. {
  454. throw new BizException("手机号、短信验证码未填写!", 2);
  455. }
  456. //如果验证通过则将验证信息缓存至redis 以防再次远程验证不通过
  457. //string uid = "";
  458. //List<Organization> organizations = GetOrgByUid(uid);
  459. //return builder.Data(organizations).build();
  460. }
  461. // [HttpPost("GetOrgByUid")]
  462. public List<Organization> GetOrgByUid(string uid)
  463. {
  464. Expression<Func<Member, bool>> mlinq = null;
  465. mlinq = m => m.unionid == uid && m.status == 1;
  466. List<Member> members = memberService.GetList(mlinq);
  467. if (members.IsNotEmpty())
  468. {
  469. Expression<Func<Organization, bool>> olinq = null;
  470. olinq = o => members.Select(x => x.orgCode).ToList().Contains(o.code) && o.status == 1;
  471. List<Organization> organizations = organizationService.GetList(olinq);
  472. ///返回前端后倒计时10秒自动选择组织机构,以防再次验证的时候 reids过期
  473. return organizations;
  474. }
  475. else { return null; }
  476. }
  477. private Dictionary<string, object> UserValid(string cellphone)
  478. {
  479. Expression<Func<Lecturer, bool>> linq = null;
  480. linq = m => m.cellphone == cellphone;
  481. List<Lecturer> lecturers = lecturerService.GetList(linq);
  482. if (lecturers.IsNotEmpty())
  483. {
  484. var lecturer = lecturers[0];
  485. ClaimModel claimModel = new ClaimModel
  486. {
  487. Scope = "WebApp"
  488. };
  489. claimModel.Claims.Add(new Claim(JwtClaimTypes.Name, lecturer.username));
  490. claimModel.Claims.Add(new Claim(JwtClaimTypes.Id, lecturer.unionid));
  491. claimModel.Claims.Add(new Claim(JwtClaimTypes.PhoneNumber, lecturer.cellphone));
  492. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  493. string role = "admin,lecturer";
  494. if (RootUsers.Contains(lecturers[0].cellphone))
  495. {
  496. role = "root," + role;
  497. }
  498. // claimModel.Claims.Add(new Claim(JwtClaimTypes.Role, role));
  499. // 可以将一个用户的多个角色全部赋予;
  500. claimModel.Claims.AddRange(role.Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
  501. // claimModel.Claims.Add(new Claim(JwtClaimTypes.ClientId, activationCodes[0].clientId));
  502. // claimModel.Claims.Add(new Claim("org", orgCode));
  503. JwtResponse jwtResponse = JwtHelper.IssueJWT(claimModel);
  504. lecturer.password = "";
  505. return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse },{ "user", lecturer } };
  506. }
  507. else
  508. {
  509. //不存在用户则新增一个
  510. Random random = new Random();
  511. string seed = new string(Constant.az09);
  512. string pfx = "";
  513. for (int i = 0; i < 4; i++)
  514. {
  515. string c = seed.ToCharArray()[random.Next(0, seed.Length)] + "";
  516. seed.Replace(c, "");
  517. pfx = pfx + c;
  518. }
  519. return new Dictionary<string, object> {
  520. { "status",1},
  521. { "user",new Lecturer
  522. {
  523. id= Guid.NewGuid().ToString(),
  524. unionid= Guid.NewGuid().ToString("N"),
  525. username=cellphone+"手机用户",
  526. password="",
  527. account="hitmd-"+cellphone.Substring(cellphone.Length-4,4)+"#"+pfx,
  528. areaCode="86",
  529. registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
  530. status=1,
  531. setaccount=0,
  532. cellphone=cellphone,
  533. avatar= "https://cdhabook.teammodel.cn/avatar/usertile"+random.Next(10, 44)+".png"
  534. }
  535. }
  536. };
  537. }
  538. }
  539. /// <summary>
  540. /// 初始化登录
  541. /// </summary>
  542. /// <param name="request"></param>
  543. /// <returns></returns>
  544. [HttpPost("init")]
  545. public BaseJosnRPCResponse Init(JosnRPCRequest<string> request)
  546. {
  547. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  548. if (!string.IsNullOrEmpty(request.@params))
  549. {
  550. var code = securityCode.GetRandomEnDigitalText(4).ToLower();
  551. var imgbyte = securityCode.GetGifEnDigitalCodeByte(code);
  552. string base64 = "data:image/png;base64," + Convert.ToBase64String(imgbyte);
  553. RedisHelper.HSet("captcha:" + request.@params, request.@params, code);
  554. RedisHelper.Expire("captcha:" + request.@params, smsTTL);
  555. return builder.Data(base64).Extend(new Dictionary<string, object> { { "code", code } }).build();
  556. }
  557. else {
  558. throw new BizException("随机码为空!", 2);
  559. }
  560. }
  561. /// <summary>
  562. /// 发送短信
  563. /// </summary>
  564. /// <param name="request"></param>
  565. /// <returns></returns>
  566. [HttpPost("sendSMS")]
  567. public async Task<BaseJosnRPCResponse> SendSMS(JosnRPCRequest<CaptchaSms> request)
  568. {
  569. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  570. string captcha = RedisHelper.HGet<string>("captcha:" + request.@params.randCode, request.@params.randCode);
  571. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  572. bool f = !string.IsNullOrEmpty(captcha) && captcha.Equals(request.@params.captcha.ToLower());
  573. bool s= RootUsers.Contains(request.@params.cellphone) && request.@params.captcha.ToLower().Equals("0000");
  574. if (f||s)
  575. {
  576. string key = request.@params.cellphone;
  577. if (RedisHelper.Exists(key))
  578. {
  579. string[] vals = RedisHelper.HVals<string>(key);
  580. if (vals != null && vals.Length > 0)
  581. {
  582. Dictionary<string, object> data = new Dictionary<string, object>() { { "msgid", vals[0] }, { "repeat", true } };
  583. return builder.Data(data).build();
  584. }
  585. else
  586. {
  587. return builder.Data(await SendMsg(key)).build();
  588. }
  589. }
  590. else
  591. {
  592. return builder.Data(await SendMsg(key)).build();
  593. }
  594. }
  595. else {
  596. throw new BizException("验证码错误!", 2);
  597. }
  598. }
  599. private static async Task<Dictionary<string, object>> SendMsg(string key)
  600. {
  601. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  602. Dictionary<string, object> data = new Dictionary<string, object>() { { "mobile", key }, { "temp_id", 1 }, { "sign_id", "" } };
  603. if (RootUsers.Contains(key))
  604. {
  605. string msgidstr = key;
  606. RedisHelper.Del(new string[] { key });
  607. RedisHelper.HSet(key, key, msgidstr);
  608. RedisHelper.Expire(key, smsTTL);
  609. return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
  610. }
  611. else {
  612. string resdata = await HttpClientHelper.Post(
  613. BaseConfigModel.Configuration["JPush:Push"],
  614. BaseConfigModel.Configuration["JPush:AppKey"],
  615. BaseConfigModel.Configuration["JPush:Secret"], data);
  616. JsonElement element = resdata.FromApiJson<JsonElement>();
  617. if (element.TryGetProperty("msg_id", out JsonElement msgid))
  618. {
  619. string msgidstr = msgid.GetString();
  620. RedisHelper.Del(new string[] { key });
  621. RedisHelper.HSet(key, key, msgidstr);
  622. RedisHelper.Expire(key, smsTTL);
  623. return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
  624. }
  625. else
  626. {
  627. throw new BizException("短信发送失败!", 2);
  628. }
  629. }
  630. }
  631. }
  632. }