AccountController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Options;
  4. using Newtonsoft.Json;
  5. using Ropin.Inspection.Api.Common;
  6. using Ropin.Inspection.Api.Common.Options;
  7. using Ropin.Inspection.Api.Common.Token;
  8. using Ropin.Inspection.Api.Wx;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Net.Http;
  13. using System.Threading.Tasks;
  14. using Ropin.Inspection.Model;
  15. using Ropin.Inspection.Service.Interface;
  16. using Ropin.Inspection.Model.ViewModel;
  17. using Ropin.Inspection.Model.SearchModel;
  18. using System.Net.Http.Headers;
  19. using Ropin.Inspection.Common.Helper;
  20. using Microsoft.AspNetCore.Http;
  21. using Ropin.Inspection.Service;
  22. using Ropin.Core.Extensions;
  23. using Ropin.Inspection.Service.SYS.Interface;
  24. using Ropin.Inspection.Model.ViewModel.SYS;
  25. using UAParser;
  26. using IPTools.Core;
  27. using Microsoft.Extensions.Caching.Memory;
  28. using Ropin.Core.Common;
  29. using Ropin.Core.Extensions.Redis;
  30. namespace Ropin.Inspection.Api.Controllers
  31. {
  32. public class AccountController : BaseController
  33. {
  34. private readonly WXOptions _options;
  35. private readonly ITsysUserService _userService;
  36. private readonly ITokenHelper _tokenHelper = null;
  37. private readonly IHttpClientFactory _httpClientFactory;
  38. private readonly ITmtnPushMsgToService _tmtnPushMsgToService;
  39. private readonly IPushMsgService _pushMsgService;
  40. private readonly ITsysRoleHandServices _roleHandServices;
  41. private readonly IsysLoginService _sysLoginService;
  42. private readonly RabbitMQModel _rabbitMQ;
  43. public AccountController(IOptionsMonitor<RabbitMQModel> rabbitMQ, IOptionsMonitor<WXOptions> options, IPushMsgService pushMsgService, ITmtnPushMsgToService tmtnPushMsgToService, IHttpClientFactory httpClientFactory, ITsysUserService userService, ITokenHelper tokenHelper, ITsysRoleHandServices roleHandServices, IsysLoginService sysLoginService, IRedisBasketRepository redisService)
  44. {
  45. _options = options.Get("WXOptions");
  46. _rabbitMQ = rabbitMQ.Get("RabbitMQModel");
  47. _userService = userService;
  48. _tokenHelper = tokenHelper;
  49. _httpClientFactory = httpClientFactory;
  50. _tmtnPushMsgToService = tmtnPushMsgToService;
  51. _pushMsgService = pushMsgService;
  52. _roleHandServices = roleHandServices;
  53. _sysLoginService = sysLoginService;
  54. RedisLimitUserLogin._redisConnection = redisService;
  55. }
  56. /// <summary>
  57. /// 微信
  58. /// </summary>
  59. /// <returns></returns>
  60. [HttpGet("GetWX/{loginCode}")]
  61. [AllowAnonymous]
  62. public async Task<ApiResult> GetWX(string loginCode)
  63. {
  64. if (string.IsNullOrEmpty(loginCode))
  65. {
  66. return new ApiResult(ReturnCode.ArgsError, "loginCode空值");
  67. }
  68. Code2Session session = null;
  69. string url = string.Format(_options.Code2Session, _options.AppId, _options.Secret, loginCode);
  70. //using (var client = _httpClientFactory.CreateClient())
  71. //{
  72. // using var res = client.GetAsync(url);
  73. // if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
  74. // {
  75. // var str = res.Result.Content.ReadAsStringAsync().Result;
  76. // session = JsonConvert.DeserializeObject<Code2Session>(str);
  77. // }
  78. //}
  79. using (var client = _httpClientFactory.CreateClient())
  80. {
  81. var requestt = new HttpRequestMessage(HttpMethod.Get, url);
  82. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  83. var response = await client.SendAsync(requestt);
  84. if (response.IsSuccessStatusCode)
  85. {
  86. var strReturn = await response.Content.ReadAsStringAsync();
  87. session = JsonConvert.DeserializeObject<Code2Session>(strReturn);
  88. }
  89. Console.WriteLine(response);
  90. }
  91. if (session == null)
  92. {
  93. return new ApiResult(ReturnCode.LoginError, "session空值");
  94. }
  95. if (string.IsNullOrEmpty(session.Openid))
  96. {
  97. return new ApiResult(ReturnCode.LoginError, "Openid空值");
  98. }
  99. //session.Openid = "ox1D95f2CfZQVkIqYTsNgrwBpKD8";
  100. //小程序返回的Openid验证
  101. TsysUserSearchModel userSearchModel = new TsysUserSearchModel { WxOpenId = session.Openid };
  102. TsysUserViewModel user = _userService.GetUser(userSearchModel);
  103. if (null == user)
  104. {
  105. LoginReturnInfo ReInfo = new LoginReturnInfo { ReturnCode = 101, OpenId = session.Openid };
  106. //return new ApiResult<string>(session.Openid, ReturnCode.PasswordLogin);
  107. return new ApiResult<LoginReturnInfo>(ReInfo, ReturnCode.Success);
  108. }
  109. TsysUserDetailViewModel user2 = await _userService.GetUserDetailByAsync(new LoginModel { Mobile = user.C_Mobile, Password = user.C_Password });
  110. var token = _tokenHelper.CreateToken(user2);
  111. if (null == token)
  112. {
  113. return new ApiResult(ReturnCode.TokenError, "获取Token异常");
  114. }
  115. LoginReturnInfo Info;
  116. //if (user.C_Password == "e10adc3949ba59abbe56e057f20f883e")
  117. // Info = new LoginReturnInfo { ReturnCode = 102, ReturnToken = token,OpenId = session.Openid };
  118. //else
  119. Info = new LoginReturnInfo { ReturnCode = 100, ReturnToken = token, OpenId = session.Openid };
  120. // 获取用户的IP地址
  121. string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
  122. // 获取浏览器信息
  123. string userAgent = Request.Headers["User-Agent"].ToString();
  124. var clientAgent = Parser.GetDefault().Parse(userAgent);
  125. var browser = $"{clientAgent.UA.Family} {clientAgent.UA.Major}.{clientAgent.UA.Minor} / {clientAgent.Device.Family}";
  126. var os = $"{clientAgent.OS.Family} {clientAgent.OS.Major} {clientAgent.OS.Minor}";
  127. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(ipAddress);
  128. sysLoginViewModel sysLogin = new sysLoginViewModel();
  129. sysLogin.C_IP = ipAddress;
  130. sysLogin.C_UserName = user.C_Name;
  131. sysLogin.C_AccountNumber = user.C_Mobile;
  132. sysLogin.C_Type = "SYS_PRIV_MODULE_002";
  133. sysLogin.C_Address = ipLocation;
  134. sysLogin.C_Browser = browser;
  135. sysLogin.C_OS = os;
  136. sysLogin.C_Role = user.UserRole.ToString();
  137. sysLogin.C_LicenseCode = user.C_LicenseCode;
  138. sysLogin.C_CreateBy = user.C_UserID.ToString();
  139. sysLogin.D_CreateOn = DateTime.Now;
  140. sysLogin.C_Status = "1";
  141. sysLogin.C_OperationInfo = "登录成功!";
  142. await _sysLoginService.CreateOneAsync(sysLogin);
  143. return new ApiResult<LoginReturnInfo>(Info, ReturnCode.Success);
  144. }
  145. /// <summary>
  146. /// 登录
  147. /// </summary>
  148. /// <param name="viewModel"></param>
  149. /// <returns></returns>
  150. [HttpPost("Login")]
  151. [AllowAnonymous]
  152. [ProducesResponseType(StatusCodes.Status200OK)]
  153. public async Task<ApiResult> Login(LoginModel viewModel)
  154. {
  155. try
  156. {
  157. var IsUser = await _userService.IsExistByMobileAsync(viewModel.Mobile);
  158. if (!IsUser)
  159. {
  160. return new ApiResult(ReturnCode.LoginError, "账户不存在!");
  161. }
  162. var isLock = await RedisLimitUserLogin.IsForbidden(viewModel.Mobile);
  163. if (isLock)
  164. {
  165. return new ApiResult(ReturnCode.LoginError, $"账户已锁定,请{RedisLimitUserLogin.LockTime}分钟后在试");
  166. }
  167. // 获取用户的IP地址
  168. string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
  169. // 获取浏览器信息
  170. string userAgent = Request.Headers["User-Agent"].ToString();
  171. var client = Parser.GetDefault().Parse(userAgent);
  172. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  173. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  174. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(ipAddress);
  175. sysLoginViewModel sysLogin = new sysLoginViewModel();
  176. sysLogin.C_IP = ipAddress;
  177. sysLogin.C_Address = ipLocation;
  178. sysLogin.C_Browser = browser;
  179. sysLogin.C_OS = os;
  180. sysLogin.C_AccountNumber = viewModel.Mobile;
  181. sysLogin.C_Type = viewModel.PrivModule;
  182. sysLogin.D_CreateOn = DateTime.Now;
  183. #region 测试
  184. //new WeChatHelper(_httpClientFactory).PushMessageToUser();
  185. #endregion
  186. var user = await _userService.GetUserDetailByAsync(viewModel);
  187. if (null == user)
  188. {
  189. int loseNumber=await RedisLimitUserLogin.SetFailCounter(viewModel.Mobile);
  190. var userMode = await _userService.GetByMobileAsync(viewModel.Mobile);
  191. sysLogin.C_UserName = userMode?.C_Name;
  192. sysLogin.C_Role = userMode?.UserRole.ToString();
  193. sysLogin.C_LicenseCode = userMode?.C_LicenseCode;
  194. sysLogin.C_CreateBy = userMode?.C_UserID.ToString();
  195. sysLogin.C_Status = "0";
  196. string msg = $"账号或密码不正确,输入错误{loseNumber} 次!";
  197. if (loseNumber== RedisLimitUserLogin.MaxAttempts)
  198. {
  199. msg = $"错误{loseNumber}次,{RedisLimitUserLogin.LockTime}分钟后再许可登录!";
  200. }
  201. sysLogin.C_OperationInfo = msg;
  202. await _sysLoginService.CreateOneAsync(sysLogin);
  203. return new ApiResult(ReturnCode.LoginError, msg);
  204. }
  205. RedisLimitUserLogin.UnLock(viewModel.Mobile);
  206. if (user.RoleTypePrivS==null|| user.RoleTypePrivS.Count()==0)
  207. {
  208. return new ApiResult(ReturnCode.LoginPriv, "没有权限");
  209. }
  210. if (!string.IsNullOrEmpty(viewModel.OpenId))
  211. {
  212. await _userService.UpdateUserOpenIdAsync(user.C_UserID, viewModel.OpenId);
  213. }
  214. Guid roleId= Guid.Parse(user.RoleIds);
  215. var roleHand = await _roleHandServices.GetRoleHandListAsync(roleId);
  216. user.RoleHandList = roleHand;
  217. var token = _tokenHelper.CreateToken(user);
  218. sysLogin.C_UserName = user.C_Name;
  219. sysLogin.C_Role = user.RoleIds;
  220. sysLogin.C_LicenseCode = user.C_LicenseCode;
  221. sysLogin.C_CreateBy = user.C_UserID.ToString();
  222. if (null == token)
  223. {
  224. sysLogin.C_Status = "0";
  225. sysLogin.C_OperationInfo = "登录失败!";
  226. await _sysLoginService.CreateOneAsync(sysLogin);
  227. return new ApiResult(ReturnCode.TokenError, "获取Token异常");
  228. }
  229. sysLogin.C_Status = "1";
  230. sysLogin.C_OperationInfo = "登录成功!";
  231. await _sysLoginService.CreateOneAsync(sysLogin);
  232. return new ApiResult<ComplexToken>(token, ReturnCode.Success);
  233. }
  234. catch (Exception ex)
  235. {
  236. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  237. }
  238. }
  239. /// <summary>
  240. /// 登出
  241. /// </summary>
  242. /// <returns></returns>
  243. [HttpPost("LogOut")]
  244. public async Task<ApiResult> LogOutByAsync()
  245. {
  246. try
  247. {
  248. // 获取用户的IP地址
  249. string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
  250. // 获取浏览器信息
  251. string userAgent = Request.Headers["User-Agent"].ToString();
  252. var client = Parser.GetDefault().Parse(userAgent);
  253. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  254. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  255. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(ipAddress);
  256. sysLoginViewModel sysLogin = new sysLoginViewModel();
  257. sysLogin.C_IP = ipAddress;
  258. sysLogin.C_Type = "";
  259. sysLogin.C_Address = ipLocation;
  260. sysLogin.C_Browser = browser;
  261. sysLogin.C_OS = os;
  262. sysLogin.C_Status = "1";
  263. sysLogin.C_OperationInfo = "退出系统!";
  264. await _sysLoginService.CreateOneAsync(sysLogin);
  265. await _userService.LogOutByAsync();
  266. return new ApiResult(ReturnCode.Success);
  267. }
  268. catch (Exception ex)
  269. {
  270. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  271. }
  272. }
  273. /// <summary>
  274. /// 测试推送消息,通过Token(可行)
  275. /// </summary>
  276. /// <returns></returns>
  277. [HttpPost("PushMessageByTokenAsync/{userWechatId}/{msg}/{token}")]
  278. [AllowAnonymous]
  279. public ApiResult PushMessageByTokenAsync(string userWechatId, string msg, string token)
  280. {
  281. try
  282. {
  283. //var content = new
  284. //{
  285. // thing2 = new { value = "niu" ?? "" },
  286. // time4 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
  287. // thing5 = new { value = "异常" ?? "" },
  288. // thing6 = new { value = "大门损坏" ?? "" },
  289. // thing9 = new { value = msg ?? "" }
  290. //};
  291. var content = new
  292. {
  293. character_string1 = new { value = "123456" ?? "" },
  294. thing2 = new { value = "niu" ?? "" },
  295. thing16 = new { value = "大门损坏" ?? "" },
  296. time5 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
  297. thing6 = new { value = "msg" ?? "" }
  298. };
  299. new WeChatHelper(_httpClientFactory).SubMessageToUser(userWechatId,token,null, content);
  300. return new ApiResult(ReturnCode.Success);
  301. }
  302. catch (Exception ex)
  303. {
  304. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  305. }
  306. }
  307. /// <summary>
  308. /// 测试推送消息,通过Wechat(可行)
  309. /// </summary>
  310. /// <param name="userWechatId"></param>
  311. /// <param name="msg"></param>
  312. /// <returns></returns>
  313. [HttpPost("PushMessageByWechatIdAsync/{userWechatId}/{msg}")]
  314. [AllowAnonymous]
  315. public ApiResult PushMessageByWechatIdAsync(string userWechatId, string msg)
  316. {
  317. try
  318. {
  319. //var content = new
  320. //{
  321. // character_string1 = new { value = "123456" ?? "" },
  322. // thing2 = new { value = "niu" ?? "" },
  323. // thing16 = new { value = "大门损坏" ?? "" },
  324. // time5 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
  325. // thing6 = new { value = msg ?? "" }
  326. //};
  327. var content = new
  328. {
  329. character_string1 = new { value = "123456" ?? "" },
  330. time2 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
  331. short_thing3 = new { value = "告警类型" ?? "" }
  332. };
  333. string templateId = WXConstModel.WatchHealthAlarm_TemplateId;
  334. new WeChatHelper(_httpClientFactory).PushMessageToUser(new List<string>() { userWechatId }, content,templateId);
  335. return new ApiResult(ReturnCode.Success);
  336. }
  337. catch (Exception ex)
  338. {
  339. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  340. }
  341. }
  342. /// <summary>
  343. /// 测试推送消息,通过devId(可行)
  344. /// </summary>
  345. /// <param name="devId"></param>
  346. /// <param name="msg"></param>
  347. /// <returns></returns>
  348. [HttpPost("PushMessageByDevIdAsync/{msg}/{devId}")]
  349. [AllowAnonymous]
  350. [HttpIdempotent(WaitMillisecond = 20000)]
  351. public async Task<ApiResult> PushMessageByDevIdAsync(string msg, string devId)
  352. {
  353. try
  354. {
  355. //_tmtnPushMsgToService.PushAlarmMsgAsync(new TpushMsgModel
  356. //{
  357. // C_DevStoreCode = devId,
  358. // C_MsgTypeCode = "MSG_TYPE_001",
  359. // Msg = msg,
  360. // Subject = "压力表维修通知"
  361. //});
  362. await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
  363. {
  364. C_DevStoreCode = devId,
  365. C_MsgTypeCode = "MSG_TYPE_023",
  366. Msg = msg,
  367. Subject = "测试推送消息",
  368. DevNumber = "boxId:",
  369. DevName = "sadf",
  370. });
  371. return new ApiResult(ReturnCode.Success);
  372. }
  373. catch (Exception ex)
  374. {
  375. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  376. }
  377. }
  378. /// <summary>
  379. /// 测试发送邮件
  380. /// </summary>
  381. /// <param name="email"></param>
  382. /// <returns></returns>
  383. [HttpPost("EmailTest/{email}")]
  384. [AllowAnonymous]
  385. public async Task<ApiResult> EmailTest(string email)
  386. {
  387. string msg = "<p><td>设备编号:</td>20250226</p>" +
  388. "<p><td>设备名称:</td>设备DevName</p>" +
  389. "<p><td>消息内容:</td>测试Email发送消息</p>"
  390. ;
  391. var bols = EmailHelper.SendEmail(email, "测试发送邮件", "测试", msg);
  392. if (bols)
  393. {
  394. return new ApiResult(ReturnCode.Success);
  395. }
  396. else
  397. {
  398. return new ApiResult(ReturnCode.GeneralError);
  399. }
  400. }
  401. /// <summary>
  402. /// 多次提交
  403. /// </summary>
  404. /// <param name="orderNo"></param>
  405. /// <returns></returns>
  406. [HttpPost("OrderAsync/{orderNo}")]
  407. [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
  408. [AllowAnonymous]
  409. public async Task<IActionResult> OrderAsync(string orderNo)
  410. {
  411. //TODO
  412. //return Content("你好");
  413. return await Task.FromResult(Ok(new
  414. {
  415. TotalCount = 10,
  416. TotalPages = 2,
  417. Orders = orderNo
  418. })) ;
  419. }
  420. /// <summary>
  421. /// 公共推送
  422. /// </summary>
  423. /// <param name="pushMsg"></param>
  424. /// <returns></returns>
  425. [HttpPost("PublicPushMessage")]
  426. [AllowAnonymous]
  427. public async Task<ApiResult> PublicPushMessage(TpushMsgModel pushMsg)
  428. {
  429. if (pushMsg == null || string.IsNullOrEmpty(pushMsg.C_MsgTypeCode) || string.IsNullOrEmpty(pushMsg.C_DevStoreCode))
  430. {
  431. return new ApiResult(ReturnCode.ArgsError);
  432. }
  433. try
  434. {
  435. _rabbitMQ.QueueName = "rab.video.record.mqtt"; //消息队列名称
  436. bool result= await _pushMsgService.PushAlarmMsgAsync(pushMsg,pushMsg.Subject, _rabbitMQ);
  437. if (result)
  438. {
  439. return new ApiResult(ReturnCode.Success);
  440. }
  441. else
  442. {
  443. return new ApiResult(ReturnCode.GeneralError);
  444. }
  445. }
  446. catch (Exception ex)
  447. {
  448. return new ApiResult(ReturnCode.GeneralError, ex.Message);
  449. }
  450. }
  451. /// <summary>
  452. /// 解析IP地址
  453. /// </summary>
  454. /// <param name="ip"></param>
  455. /// <returns></returns>
  456. [NonAction]
  457. internal static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  458. {
  459. try
  460. {
  461. var ipInfo = IpTool.Search(ip);
  462. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  463. return (string.Join("|", addressList.Where(it => it != "0").ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0并用|连接
  464. }
  465. catch(Exception ex)
  466. {
  467. // 不做处理
  468. }
  469. return ("未知", 0, 0);
  470. }
  471. }
  472. }