LoginController.cs 33 KB

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