PassportController.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using Masuit.MyBlogs.Core.Common;
  2. using Masuit.MyBlogs.Core.Configs;
  3. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  4. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  5. using Masuit.MyBlogs.Core.Models.DTO;
  6. using Masuit.MyBlogs.Core.Models.Enum;
  7. using Masuit.MyBlogs.Core.Models.ViewModel;
  8. using Masuit.Tools;
  9. using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
  10. using Masuit.Tools.Core.Net;
  11. using Masuit.Tools.Security;
  12. using Masuit.Tools.Strings;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Mvc;
  15. using System;
  16. using System.Web;
  17. namespace Masuit.MyBlogs.Core.Controllers
  18. {
  19. /// <summary>
  20. /// 登录授权
  21. /// </summary>
  22. [ApiExplorerSettings(IgnoreApi = true)]
  23. public class PassportController : Controller
  24. {
  25. /// <summary>
  26. /// 用户
  27. /// </summary>
  28. public IUserInfoService UserInfoService { get; set; }
  29. /// <summary>
  30. /// 客户端的真实IP
  31. /// </summary>
  32. public string ClientIP => HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
  33. /// <summary>
  34. ///
  35. /// </summary>
  36. /// <param name="data"></param>
  37. /// <param name="isTrue"></param>
  38. /// <param name="message"></param>
  39. /// <returns></returns>
  40. public ActionResult ResultData(object data, bool isTrue = true, string message = "")
  41. {
  42. return Json(new
  43. {
  44. Success = isTrue,
  45. Message = message,
  46. Data = data
  47. });
  48. }
  49. /// <summary>
  50. /// 登录页
  51. /// </summary>
  52. /// <returns></returns>
  53. public ActionResult Login()
  54. {
  55. var keys = RsaCrypt.GenerateRsaKeys(RsaKeyType.PEM);
  56. Response.Cookies.Append("PublicKey", keys.PublicKey);
  57. HttpContext.Session.Set("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);
  63. }
  64. if (HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) != null)
  65. {
  66. if (string.IsNullOrEmpty(from))
  67. {
  68. return RedirectToAction("Index", "Home");
  69. }
  70. return LocalRedirect(from);
  71. }
  72. if (Request.Cookies.Count > 2)
  73. {
  74. string name = Request.Cookies["username"];
  75. string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK);
  76. var userInfo = UserInfoService.Login(name, pwd);
  77. if (userInfo != null)
  78. {
  79. Response.Cookies.Append("username", name, new CookieOptions()
  80. {
  81. Expires = DateTime.Now.AddDays(7),
  82. SameSite = SameSiteMode.Lax
  83. });
  84. Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions()
  85. {
  86. Expires = DateTime.Now.AddDays(7),
  87. SameSite = SameSiteMode.Lax
  88. });
  89. HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
  90. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default);
  91. if (string.IsNullOrEmpty(from))
  92. {
  93. return RedirectToAction("Index", "Home");
  94. }
  95. return LocalRedirect(from);
  96. }
  97. }
  98. return View();
  99. }
  100. /// <summary>
  101. /// 登陆检查
  102. /// </summary>
  103. /// <param name="username"></param>
  104. /// <param name="password"></param>
  105. /// <param name="valid"></param>
  106. /// <param name="remem"></param>
  107. /// <returns></returns>
  108. [HttpPost, ValidateAntiForgeryToken]
  109. public ActionResult Login(string username, string password, string valid, string remem)
  110. {
  111. string validSession = HttpContext.Session.Get<string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较
  112. if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
  113. {
  114. return ResultData(null, false, "验证码错误");
  115. }
  116. HttpContext.Session.Remove("valid"); //验证成功就销毁验证码Session,非常重要
  117. if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim()))
  118. {
  119. return ResultData(null, false, "用户名或密码不能为空");
  120. }
  121. password = password.RSADecrypt(HttpContext.Session.Get<string>("PrivateKey"));
  122. var userInfo = UserInfoService.Login(username, password);
  123. if (userInfo == null)
  124. {
  125. return ResultData(null, false, "用户名或密码错误");
  126. }
  127. HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
  128. if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录
  129. {
  130. Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions()
  131. {
  132. Expires = DateTime.Now.AddDays(7),
  133. SameSite = SameSiteMode.Lax
  134. });
  135. Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions()
  136. {
  137. Expires = DateTime.Now.AddDays(7),
  138. SameSite = SameSiteMode.Lax
  139. });
  140. }
  141. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default);
  142. string refer = Request.Cookies["refer"];
  143. Response.Cookies.Delete(nameof(RsaKey.PublicKey));
  144. Response.Cookies.Delete("refer");
  145. HttpContext.Session.Remove(nameof(RsaKey.PrivateKey));
  146. return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer);
  147. }
  148. /// <summary>
  149. /// 生成验证码
  150. /// </summary>
  151. /// <returns></returns>
  152. public ActionResult ValidateCode()
  153. {
  154. string code = Tools.Strings.ValidateCode.CreateValidateCode(6);
  155. HttpContext.Session.Set("valid", code); //将验证码生成到Session中
  156. var buffer = HttpContext.CreateValidateGraphic(code);
  157. return this.ResumeFile(buffer, "image/jpeg");
  158. }
  159. /// <summary>
  160. /// 检查验证码
  161. /// </summary>
  162. /// <param name="code"></param>
  163. /// <returns></returns>
  164. [HttpPost]
  165. public ActionResult CheckValidateCode(string code)
  166. {
  167. string validSession = HttpContext.Session.Get<string>("valid");
  168. if (string.IsNullOrEmpty(validSession) || !code.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
  169. {
  170. return ResultData(null, false, "验证码错误");
  171. }
  172. return ResultData(null, false, "验证码正确");
  173. }
  174. /// <summary>
  175. /// 获取用户信息
  176. /// </summary>
  177. /// <returns></returns>
  178. public ActionResult GetUserInfo()
  179. {
  180. var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
  181. #if DEBUG
  182. user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoDto>();
  183. #endif
  184. return ResultData(user);
  185. }
  186. /// <summary>
  187. /// 注销登录
  188. /// </summary>
  189. /// <returns></returns>
  190. public ActionResult Logout()
  191. {
  192. HttpContext.Session.Remove(SessionKey.UserInfo);
  193. Response.Cookies.Delete("username");
  194. Response.Cookies.Delete("password");
  195. HttpContext.Session.Clear();
  196. return Request.Method.Equals(HttpMethods.Get) ? RedirectToAction("Index", "Home") : ResultData(null, message: "注销成功!");
  197. }
  198. }
  199. }