LoginController.cs 30 KB

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