BaseController.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using AutoMapper;
  2. using Masuit.MyBlogs.Core.Common;
  3. using Masuit.MyBlogs.Core.Configs;
  4. using Masuit.MyBlogs.Core.Extensions;
  5. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  6. using Masuit.MyBlogs.Core.Models.DTO;
  7. using Masuit.MyBlogs.Core.Models.Enum;
  8. using Masuit.MyBlogs.Core.Models.ViewModel;
  9. using Masuit.Tools.Core.Net;
  10. using Masuit.Tools.Security;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.AspNetCore.Mvc.Filters;
  14. using Microsoft.EntityFrameworkCore.Internal;
  15. using System;
  16. using System.Linq;
  17. using System.Net;
  18. using Masuit.MyBlogs.Core.Extensions.Firewall;
  19. namespace Masuit.MyBlogs.Core.Controllers
  20. {
  21. /// <summary>
  22. /// 基本父控制器
  23. /// </summary>
  24. [ApiExplorerSettings(IgnoreApi = true), ServiceFilter(typeof(FirewallAttribute))]
  25. public class BaseController : Controller
  26. {
  27. /// <summary>
  28. /// UserInfoService
  29. /// </summary>
  30. public IUserInfoService UserInfoService { get; set; }
  31. /// <summary>
  32. /// MenuService
  33. /// </summary>
  34. public IMenuService MenuService { get; set; }
  35. /// <summary>
  36. /// LinksService
  37. /// </summary>
  38. public ILinksService LinksService { get; set; }
  39. public IAdvertisementService AdsService { get; set; }
  40. public UserInfoDto CurrentUser => HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
  41. /// <summary>
  42. /// 客户端的真实IP
  43. /// </summary>
  44. public string ClientIP
  45. {
  46. get
  47. {
  48. var ip = HttpContext.Connection.RemoteIpAddress.ToString();
  49. var trueip = Request.Headers[AppConfig.TrueClientIPHeader].ToString();
  50. if (!string.IsNullOrEmpty(trueip) && ip != trueip)
  51. {
  52. ip = trueip;
  53. }
  54. return ip;
  55. }
  56. }
  57. /// <summary>
  58. /// 普通访客是否token合法
  59. /// </summary>
  60. public bool VisitorTokenValid => Request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(Request.Cookies["FullAccessToken"]);
  61. public IMapper Mapper { get; set; }
  62. public MapperConfiguration MapperConfig { get; set; }
  63. /// <summary>
  64. /// 响应数据
  65. /// </summary>
  66. /// <param name="data">数据</param>
  67. /// <param name="success">响应状态</param>
  68. /// <param name="message">响应消息</param>
  69. /// <param name="isLogin">登录状态</param>
  70. /// <param name="code">http响应码</param>
  71. /// <returns></returns>
  72. public ActionResult ResultData(object data, bool success = true, string message = "", bool isLogin = true, HttpStatusCode code = HttpStatusCode.OK)
  73. {
  74. return Ok(new
  75. {
  76. IsLogin = isLogin,
  77. Success = success,
  78. Message = message,
  79. Data = data,
  80. code
  81. });
  82. }
  83. /// <summary>在调用操作方法前调用。</summary>
  84. /// <param name="filterContext">有关当前请求和操作的信息。</param>
  85. public override void OnActionExecuting(ActionExecutingContext filterContext)
  86. {
  87. base.OnActionExecuting(filterContext);
  88. var user = filterContext.HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
  89. #if DEBUG
  90. user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoDto>();
  91. filterContext.HttpContext.Session.Set(SessionKey.UserInfo, user);
  92. #endif
  93. if (CommonHelper.SystemSettings.GetOrAdd("CloseSite", "false") == "true" && user?.IsAdmin != true)
  94. {
  95. filterContext.Result = RedirectToAction("ComingSoon", "Error");
  96. }
  97. if (Request.Method == HttpMethods.Post && !Request.Path.Value.Contains("get", StringComparison.InvariantCultureIgnoreCase) && CommonHelper.SystemSettings.GetOrAdd("DataReadonly", "false") == "true" && !filterContext.Filters.Any(m => m.ToString().Contains(nameof(MyAuthorizeAttribute))))
  98. {
  99. filterContext.Result = ResultData("网站当前处于数据写保护状态,无法提交任何数据,如有疑问请联系网站管理员!", false, "网站当前处于数据写保护状态,无法提交任何数据,如有疑问请联系网站管理员!", user != null, HttpStatusCode.BadRequest);
  100. }
  101. if (user == null && Request.Cookies.Any(x => x.Key == "username" || x.Key == "password")) //执行自动登录
  102. {
  103. string name = Request.Cookies["username"];
  104. string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK);
  105. var userInfo = UserInfoService.Login(name, pwd);
  106. if (userInfo != null)
  107. {
  108. Response.Cookies.Append("username", name, new CookieOptions
  109. {
  110. Expires = DateTime.Now.AddDays(7),
  111. SameSite = SameSiteMode.Lax
  112. });
  113. Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions
  114. {
  115. Expires = DateTime.Now.AddDays(7),
  116. SameSite = SameSiteMode.Lax
  117. });
  118. filterContext.HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
  119. }
  120. }
  121. if (ModelState.IsValid) return;
  122. var errmsgs = ModelState.SelectMany(kv => kv.Value.Errors.Select(e => e.ErrorMessage)).ToList();
  123. if (errmsgs.Any())
  124. {
  125. for (var i = 0; i < errmsgs.Count; i++)
  126. {
  127. errmsgs[i] = i + 1 + ". " + errmsgs[i];
  128. }
  129. }
  130. filterContext.Result = ResultData(errmsgs, false, "数据校验失败,错误信息:" + errmsgs.Join(" | "), user != null, HttpStatusCode.BadRequest);
  131. }
  132. /// <summary>在调用操作方法后调用。</summary>
  133. /// <param name="filterContext">有关当前请求和操作的信息。</param>
  134. public override void OnActionExecuted(ActionExecutedContext filterContext)
  135. {
  136. base.OnActionExecuted(filterContext);
  137. if (filterContext.HttpContext.Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
  138. {
  139. if (filterContext.Result is ViewResult)
  140. {
  141. filterContext.Result = ResultData(null, false, "该URL仅支持Get请求方式", false, HttpStatusCode.MethodNotAllowed);
  142. }
  143. return;
  144. }
  145. ViewBag.menus = MenuService.GetQueryFromCache<MenuDto>(m => m.Status == Status.Available).OrderBy(m => m.Sort).ToList(); //菜单
  146. var model = new PageFootViewModel //页脚
  147. {
  148. Links = LinksService.GetQueryFromCache<LinksDto>(l => l.Status == Status.Available).OrderByDescending(l => l.Recommend).ThenByDescending(l => l.Weight).ThenByDescending(l => new Random().Next()).Take(30).ToList()
  149. };
  150. ViewBag.Footer = model;
  151. }
  152. }
  153. }