PassportController.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using AutoMapper;
  2. using CacheManager.Core;
  3. using Hangfire;
  4. using Masuit.MyBlogs.Core.Configs;
  5. using Masuit.MyBlogs.Core.Extensions.Firewall;
  6. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  7. using Masuit.Tools.Mime;
  8. using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
  9. using Masuit.Tools.Logging;
  10. using Microsoft.AspNetCore.Mvc;
  11. using System.Net;
  12. using System.Web;
  13. namespace Masuit.MyBlogs.Core.Controllers;
  14. /// <summary>
  15. /// 登录授权
  16. /// </summary>
  17. [ApiExplorerSettings(IgnoreApi = true), ServiceFilter(typeof(FirewallAttribute))]
  18. public sealed class PassportController : Controller
  19. {
  20. /// <summary>
  21. /// 用户
  22. /// </summary>
  23. public IUserInfoService UserInfoService { get; set; }
  24. public IFirewallRepoter FirewallRepoter { get; set; }
  25. public IMapper Mapper { get; set; }
  26. /// <summary>
  27. /// 客户端的真实IP
  28. /// </summary>
  29. public string ClientIP => HttpContext.Connection.RemoteIpAddress.ToString();
  30. /// <summary>
  31. ///
  32. /// </summary>
  33. /// <param name="data"></param>
  34. /// <param name="isTrue"></param>
  35. /// <param name="message"></param>
  36. /// <returns></returns>
  37. private ActionResult ResultData(object data, bool isTrue = true, string message = "")
  38. {
  39. return Json(new
  40. {
  41. Success = isTrue,
  42. Message = message,
  43. Data = data
  44. });
  45. }
  46. /// <summary>
  47. /// 登录页
  48. /// </summary>
  49. /// <returns></returns>
  50. public ActionResult Login()
  51. {
  52. var keys = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS1);
  53. Response.Cookies.Append(nameof(keys.PublicKey), keys.PublicKey, new CookieOptions()
  54. {
  55. SameSite = SameSiteMode.Lax
  56. });
  57. HttpContext.Session.Set(nameof(keys.PrivateKey), keys.PrivateKey);
  58. string from = Request.Query["from"];
  59. if (!string.IsNullOrEmpty(from))
  60. {
  61. from = HttpUtility.UrlDecode(from);
  62. Response.Cookies.Append("refer", from, new CookieOptions()
  63. {
  64. SameSite = SameSiteMode.Lax
  65. });
  66. }
  67. if (HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) != null)
  68. {
  69. if (string.IsNullOrEmpty(from))
  70. {
  71. return RedirectToAction("Index", "Home");
  72. }
  73. return LocalRedirect(from);
  74. }
  75. if (Request.Cookies.Count > 2)
  76. {
  77. string name = Request.Cookies["username"];
  78. string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK);
  79. var userInfo = UserInfoService.Login(name, pwd);
  80. if (userInfo != null)
  81. {
  82. Response.Cookies.Append("username", name, new CookieOptions()
  83. {
  84. Expires = DateTime.Now.AddYears(1),
  85. SameSite = SameSiteMode.Lax
  86. });
  87. Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions()
  88. {
  89. Expires = DateTime.Now.AddYears(1),
  90. SameSite = SameSiteMode.Lax
  91. });
  92. HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
  93. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default));
  94. if (string.IsNullOrEmpty(from))
  95. {
  96. return RedirectToAction("Index", "Home");
  97. }
  98. return LocalRedirect(from);
  99. }
  100. }
  101. return View();
  102. }
  103. /// <summary>
  104. /// 登陆检查
  105. /// </summary>
  106. /// <param name="username"></param>
  107. /// <param name="password"></param>
  108. /// <param name="valid"></param>
  109. /// <param name="remem"></param>
  110. /// <returns></returns>
  111. [HttpPost, ValidateAntiForgeryToken]
  112. public ActionResult Login([FromServices] ICacheManager<int> cacheManager, string username, string password, string valid, string remem)
  113. {
  114. string validSession = HttpContext.Session.Get<string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较
  115. if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
  116. {
  117. return ResultData(null, false, "验证码错误");
  118. }
  119. HttpContext.Session.Remove("valid"); //验证成功就销毁验证码Session,非常重要
  120. if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim()))
  121. {
  122. return ResultData(null, false, "用户名或密码不能为空");
  123. }
  124. try
  125. {
  126. var privateKey = HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey));
  127. password = password.RSADecrypt(privateKey);
  128. }
  129. catch (Exception)
  130. {
  131. LogManager.Info("登录失败,私钥:" + HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey)));
  132. throw;
  133. }
  134. var userInfo = UserInfoService.Login(username, password);
  135. if (userInfo == null)
  136. {
  137. var times = cacheManager.AddOrUpdate("LoginError:" + ClientIP, 1, i => i + 1, 5);
  138. if (times > 30)
  139. {
  140. FirewallRepoter.ReportAsync(IPAddress.Parse(ClientIP)).ContinueWith(_ => LogManager.Info($"多次登录用户名或密码错误,疑似爆破行为,已上报IP{ClientIP}至:" + FirewallRepoter.ReporterName));
  141. }
  142. return ResultData(null, false, "用户名或密码错误");
  143. }
  144. HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
  145. if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录
  146. {
  147. Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions()
  148. {
  149. Expires = DateTime.Now.AddYears(1),
  150. SameSite = SameSiteMode.Lax
  151. });
  152. Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions()
  153. {
  154. Expires = DateTime.Now.AddYears(1),
  155. SameSite = SameSiteMode.Lax
  156. });
  157. }
  158. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default));
  159. string refer = Request.Cookies["refer"];
  160. Response.Cookies.Delete(nameof(RsaKey.PublicKey), new CookieOptions()
  161. {
  162. SameSite = SameSiteMode.Lax
  163. });
  164. Response.Cookies.Delete("refer", new CookieOptions()
  165. {
  166. SameSite = SameSiteMode.Lax
  167. });
  168. HttpContext.Session.Remove(nameof(RsaKey.PrivateKey));
  169. return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer);
  170. }
  171. /// <summary>
  172. /// 生成验证码
  173. /// </summary>
  174. /// <returns></returns>
  175. public ActionResult ValidateCode()
  176. {
  177. string code = Tools.Strings.ValidateCode.CreateValidateCode(6);
  178. HttpContext.Session.Set("valid", code); //将验证码生成到Session中
  179. using var buffer = code.CreateValidateGraphic();
  180. return this.ResumeFile(buffer, ContentType.Jpeg, "验证码.jpg");
  181. }
  182. /// <summary>
  183. /// 检查验证码
  184. /// </summary>
  185. /// <param name="code"></param>
  186. /// <returns></returns>
  187. [HttpPost]
  188. public ActionResult CheckValidateCode(string code)
  189. {
  190. string validSession = HttpContext.Session.Get<string>("valid");
  191. if (string.IsNullOrEmpty(validSession) || !code.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
  192. {
  193. return ResultData(null, false, "验证码错误");
  194. }
  195. return ResultData(null, false, "验证码正确");
  196. }
  197. /// <summary>
  198. /// 获取用户信息
  199. /// </summary>
  200. /// <returns></returns>
  201. public ActionResult GetUserInfo()
  202. {
  203. var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
  204. #if DEBUG
  205. user = Mapper.Map<UserInfoDto>(UserInfoService.GetByUsername("masuit"));
  206. #endif
  207. return ResultData(user);
  208. }
  209. /// <summary>
  210. /// 注销登录
  211. /// </summary>
  212. /// <returns></returns>
  213. public ActionResult Logout()
  214. {
  215. HttpContext.Session.Remove(SessionKey.UserInfo);
  216. Response.Cookies.Delete("username", new CookieOptions()
  217. {
  218. SameSite = SameSiteMode.Lax
  219. });
  220. Response.Cookies.Delete("password", new CookieOptions()
  221. {
  222. SameSite = SameSiteMode.Lax
  223. });
  224. HttpContext.Session.Clear();
  225. return Request.Method.Equals(HttpMethods.Get) ? RedirectToAction("Index", "Home") : ResultData(null, message: "注销成功!");
  226. }
  227. }