public ActionResult Login(string username, string password, string valid, string remem) { string validSession = Session.GetByRedis <string>("valid") ?? String.Empty; //将验证码从Session中取出来,用于登录验证比较 if (String.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return(ResultData(null, false, "验证码错误")); } Session.RemoveByRedis("valid"); //验证成功就销毁验证码Session,非常重要 if (String.IsNullOrEmpty(username.Trim()) || String.IsNullOrEmpty(password.Trim())) { return(ResultData(null, false, "用户名或密码不能为空")); } var userInfo = UserInfoBll.Login(username, password); if (userInfo != null) { Session.SetByRedis(SessionKey.UserInfo, userInfo); if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录 { HttpCookie userCookie = new HttpCookie("username", Server.UrlEncode(username.Trim())); Response.Cookies.Add(userCookie); userCookie.Expires = DateTime.Now.AddDays(7); HttpCookie passCookie = new HttpCookie("password", password.Trim().DesEncrypt(ConfigurationManager.AppSettings["BaiduAK"])) { Expires = DateTime.Now.AddDays(7) }; Response.Cookies.Add(passCookie); } HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, Request.UserHostAddress, LoginType.Default); string refer = CookieHelper.GetCookieValue("refer"); if (string.IsNullOrEmpty(refer)) { return(ResultData(null, true, "/")); } return(ResultData(null, true, refer)); } return(ResultData(null, false, "用户名或密码错误")); }
public async Task <ActionResult> Details(int id, string kw) { var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到"); ViewBag.Keyword = post.Keyword + "," + post.Label; var modifyDate = post.ModifyDate; ViewBag.Next = PostService.GetFromCache <DateTime, PostModelBase>(p => p.ModifyDate > modifyDate && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate); ViewBag.Prev = PostService.GetFromCache <DateTime, PostModelBase>(p => p.ModifyDate < modifyDate && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate, false); if (!string.IsNullOrEmpty(kw)) { ViewData["keywords"] = post.Content.Contains(kw) ? $"['{kw}']" : SearchEngine.LuceneIndexSearcher.CutKeywords(kw).ToJsonString(); } ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, post.CategoryId); var related = PostService.ScoreSearch(1, 11, string.IsNullOrWhiteSpace(post.Keyword + post.Label) ? post.Title : post.Keyword + post.Label); related.RemoveAll(p => p.Id == id); if (related.Count <= 1) { related = (await PostService.GetPagesFromCacheAsync(1, 10, p => p.Id != id && p.CategoryId == post.CategoryId, p => p.TotalViewCount, false)).Data; } ViewBag.Related = related; post.ModifyDate = post.ModifyDate.ToTimeZone(HttpContext.Session.Get <string>(SessionKey.TimeZone)); post.PostDate = post.PostDate.ToTimeZone(HttpContext.Session.Get <string>(SessionKey.TimeZone)); if (CurrentUser.IsAdmin) { return(View("Details_Admin", post)); } if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get <string>("post" + id))) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id); HttpContext.Session.Set("post" + id, id.ToString()); } return(View(post)); }
/// <summary> /// 登录页 /// </summary> /// <returns></returns> public ActionResult Login() { string from = Request.Query["from"]; if (!string.IsNullOrEmpty(from)) { from = HttpUtility.UrlDecode(from); Response.Cookies.Append("refer", from); } if (HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) != null) { if (string.IsNullOrEmpty(from)) { return RedirectToAction("Index", "Home"); } return Redirect(from); } if (Request.Cookies.Count > 2) { string name = Request.Cookies["username"]; string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK); var userInfo = UserInfoService.Login(name, pwd); if (userInfo != null) { Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddDays(7) }); Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions() { Expires = DateTime.Now.AddDays(7) }); HttpContext.Session.Set(SessionKey.UserInfo, userInfo); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default); if (string.IsNullOrEmpty(from)) { return RedirectToAction("Index", "Home"); } return Redirect(from); } } return View(); }
public ActionResult Login(string username, string password, string valid, string remem) { string validSession = HttpContext.Session.Get <string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较 if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return(ResultData(null, false, "验证码错误")); } HttpContext.Session.Remove("valid"); //验证成功就销毁验证码Session,非常重要 if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim())) { return(ResultData(null, false, "用户名或密码不能为空")); } var userInfo = UserInfoService.Login(username, password); if (userInfo == null) { return(ResultData(null, false, "用户名或密码错误")); } HttpContext.Session.Set(SessionKey.UserInfo, userInfo); if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录 { Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions() { Expires = DateTime.Now.AddDays(7) }); Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddDays(7) }); } HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default); string refer = Request.Cookies["refer"]; return(ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer)); }
public ActionResult Details(int id, string kw) { Post post = PostService.GetById(id); if (post != null) { ViewBag.Keyword = post.Keyword + "," + post.Label; UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto(); DateTime modifyDate = post.ModifyDate; ViewBag.Next = PostService.GetFirstEntity <DateTime, PostModelBase>(p => p.ModifyDate > modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate); ViewBag.Prev = PostService.GetFirstEntity <DateTime, PostModelBase>(p => p.ModifyDate < modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate, false); if (!string.IsNullOrEmpty(kw)) { ViewData["keywords"] = post.Content.Contains(kw) ? $"['{kw}']" : SearchEngine.LuceneIndexSearcher.CutKeywords(kw).ToJsonString(); } if (user.IsAdmin) { return(View("Details_Admin", post)); } if (post.Status != Status.Pended) { return(RedirectToAction("Post", "Home")); } if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get <string>("post" + id))) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id); HttpContext.Session.Set("post" + id, id.ToString()); } return(View(post)); } return(RedirectToAction("Index", "Error")); }
public ActionResult Login() { string from = Request["from"]; if (!string.IsNullOrEmpty(from)) { from = Server.UrlDecode(from); CookieHelper.SetCookie("refer", from); } if (Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo) != null) { if (string.IsNullOrEmpty(from)) { return(RedirectToAction("Index", "Home")); } return(Redirect(from)); } if (Request.Cookies.Count > 2) { string name = CookieHelper.GetCookieValue("username"); string pwd = CookieHelper.GetCookieValue("password")?.DesDecrypt(ConfigurationManager.AppSettings["BaiduAK"]); var userInfo = UserInfoBll.Login(name, pwd); if (userInfo != null) { CookieHelper.SetCookie("username", name, DateTime.Now.AddDays(7)); CookieHelper.SetCookie("password", CookieHelper.GetCookieValue("password"), DateTime.Now.AddDays(7)); Session.SetByRedis(SessionKey.UserInfo, userInfo); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, Request.UserHostAddress, LoginType.Default); if (string.IsNullOrEmpty(from)) { return(RedirectToAction("Index", "Home")); } return(Redirect(from)); } } return(View()); }
/// <summary> /// 每周任务 /// </summary> public static void EveryweekJob() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.CreateLuceneIndex), "default"); }
/// <summary> /// 每日任务 /// </summary> public static void EverydayJob() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.EverydayJob), "default"); }
/// <summary> /// 检查友链 /// </summary> public static void CheckLinks() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.CheckLinks), "default"); }
/// <summary> /// 每小时任务 /// </summary> public static void EveryHourJob() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.StatisticsSearchKeywords), "default"); }
public async Task Invoke(HttpContext context) { var request = context.Request; if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP()) { context.Response.StatusCode = 404; return; } var ip = context.GetTrueIP(); context.Items.AddOrUpdate("ip.asn", ip.GetIPAsn()); context.Items.AddOrUpdate("ip.location", ip.GetIPLocation()); var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8); var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path); var match = Regex.Match(path ?? "", CommonHelper.BanRegex); if (match.Length > 0) { BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter() { IP = ip, RequestUrl = requestUrl, Time = DateTime.Now, UserAgent = request.Headers[HeaderNames.UserAgent], Remark = $"检测到敏感词拦截:{match.Value}" })); context.Response.StatusCode = 400; await context.Response.WriteAsync("参数不合法!", Encoding.UTF8); return; } if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot()) { context.Session.Set("session", 0); var referer = context.Request.Headers[HeaderNames.Referer].ToString(); if (!string.IsNullOrEmpty(referer)) { try { new Uri(referer);//判断是不是一个合法的referer if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" })) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: referer); } } catch { context.Response.StatusCode = 504; await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8); return; } } } if (!context.Request.IsRobot()) { if (request.QueryString.HasValue) { var q = request.QueryString.Value.Trim('?'); requestUrl = requestUrl.Replace(q, q.Split('&').Where(s => !s.StartsWith("cid") && !s.StartsWith("uid")).Join("&")); } TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog() { Count = 1, RequestUrls = { requestUrl }, UserAgents = { request.Headers[HeaderNames.UserAgent] } }, (s, i) => { i.UserAgents.Add(request.Headers[HeaderNames.UserAgent]); i.RequestUrls.Add(requestUrl); i.Count++; return(i); }); } if (string.IsNullOrEmpty(context.Session.Get <string>(SessionKey.TimeZone))) { context.Session.Set(SessionKey.TimeZone, context.Connection.RemoteIpAddress.GetClientTimeZone()); } await _next(context); }
public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false) { post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes()); if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available)) { return(ResultData(null, message: "请选择一个分类")); } if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null")) { post.Label = null; } else if (post.Label.Trim().Length > 50) { post.Label = post.Label.Replace(",", ","); post.Label = post.Label.Trim().Substring(0, 50); } else { post.Label = post.Label.Replace(",", ","); } if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase)) { post.ProtectContent = null; } post.Status = Status.Published; Post p = post.Mapper <Post>(); p.Modifier = p.Author; p.ModifierEmail = p.Email; p.IP = ClientIP; if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); foreach (var s in tmp) { var id = s.ToInt32(); Seminar seminar = await SeminarService.GetByIdAsync(id); p.Seminar.Add(new SeminarPost() { Post = p, PostId = p.Id, Seminar = seminar, SeminarId = seminar.Id }); } } if (schedule) { if (!timespan.HasValue || timespan.Value <= DateTime.Now) { return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } p.Status = Status.Schedule; p.PostDate = timespan.Value; p.ModifyDate = timespan.Value; HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p); return(ResultData(p.Mapper <PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!")); } PostService.AddEntity(p); bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章发表失败!")); } return(ResultData(null, true, "文章发表成功!")); }
public ActionResult ResetIndex() { string job = HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.ResetLucene)); return(ResultData(job, true, "索引库重置成功!")); }
protected void Session_Start(object sender, EventArgs e) { HttpRequest request = Request; string ua = request.UserAgent; string ip = request.UserHostAddress; #if DEBUG Random r = new Random(); ip = $"{r.StrictNext(235)}.{r.StrictNext(255)}.{r.StrictNext(255)}.{r.StrictNext(255)}"; #endif Session.Set("landDate", DateTime.Now); ip.MatchInetAddress(out bool success); if (success) { Guid uid = Guid.NewGuid(); Session.Set("currentOnline", uid); Task.Factory.StartNew(s => { HttpRequest req = s as HttpRequest; bool isNotSpider = ua != null && !ua.Contains(new[] { "DNSPod", "Baidu", "spider", "Python", "bot" }); if (isNotSpider) //屏蔽百度云观测以及搜索引擎爬虫 { string refer; try { refer = req.UrlReferrer?.AbsoluteUri ?? "直接输入网址"; } catch (Exception) { refer = "直接输入网址"; } string browserType = req.Browser.Type; if (browserType.Contains("Chrome1") || browserType.Contains("Chrome2") || browserType.Contains("Chrome3") || browserType.Equals("Chrome4") || browserType.Equals("Chrome7") || browserType.Equals("Chrome9") || browserType.Contains("Chrome40") || browserType.Contains("Chrome41") || browserType.Contains("Chrome42") || browserType.Contains("Chrome43")) { browserType = "Chrome43-"; } else if (browserType.Contains("IE")) { browserType = "InternetExplorer" + req.Browser.Version; } else if (browserType.Equals("Safari6") || browserType.Equals("Safari5") || browserType.Equals("Safari4") || browserType.Equals("Safari")) { browserType = "Safari6-"; } Interview interview = new Interview() { IP = ip, UserAgent = ua, BrowserType = browserType, OperatingSystem = req.Browser.Platform, ViewTime = DateTime.Now, FromUrl = refer, HttpMethod = req.HttpMethod, LandPage = req.Url.ToString(), Uid = uid }; HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.FlushInetAddress), args: interview); } }, request); } }
public ActionResult Edit(PostInputDto post, string Seminars, bool notify = true) { post.Content = ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/"); if (!CategoryBll.Any(c => c.Id == post.CategoryId && c.Status == Status.Available)) { return(ResultData(null, message: "请选择一个分类")); } if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null")) { post.Label = null; } else if (post.Label.Trim().Length > 50) { post.Label = post.Label.Replace(",", ","); post.Label = post.Label.Trim().Substring(0, 50); } else { post.Label = post.Label.Replace(",", ","); } if (!post.IsWordDocument) { post.ResourceName = null; } if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase)) { post.ProtectContent = null; } post.ModifyDate = DateTime.Now; Post p = PostBll.GetById(post.Id); var history = p.Mapper <PostHistoryVersion>(); p.PostHistoryVersion.Add(history); Mapper.Map(post, p); if (!string.IsNullOrEmpty(Seminars)) { var tmp = Seminars.Split(',').Distinct(); p.Seminar.Clear(); tmp.ForEach(s => { p.Seminar.Add(SeminarBll.GetFirstEntity(e => e.Title.Equals(s))); }); } bool b = PostBll.UpdateEntitySaved(p); if (b) { #if !DEBUG if (notify) { var cast = BroadcastBll.LoadEntities(c => c.Status == Status.Subscribed).ToList(); string link = Request.Url?.Scheme + "://" + Request.Url?.Authority + "/" + p.Id; cast.ForEach(c => { var ts = DateTime.Now.GetTotalMilliseconds(); string content = System.IO.File.ReadAllText(Request.MapPath("/template/broadcast.html")).Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.PostDate.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", post.Title).Replace("{{author}}", post.Author).Replace("{{content}}", post.Content.RemoveHtmlTag(150)).Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new { c.Email, act = "cancel", validate = c.ValidateCode, timespan = ts, hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(ConfigurationManager.AppSettings["BaiduAK"]) }, Request.Url.Scheme)); BackgroundJob.Schedule(() => SendMail(GetSettings("Title") + "博客有新文章发布了", content, c.Email), (p.PostDate - DateTime.Now)); }); } #endif HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); return(ResultData(p.Mapper <PostOutputDto>(), message: "文章修改成功!")); } return(ResultData(null, false, "文章修改失败!")); }
public ActionResult Write(PostInputDto post, string Seminars, DateTime?timespan, bool schedule = false) { post.Content = ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");//提取img标签,提取src属性并重新创建个只包含src属性的img标签 if (!CategoryBll.Any(c => c.Id == post.CategoryId && c.Status == Status.Available)) { return(ResultData(null, message: "请选择一个分类")); } if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null")) { post.Label = null; } else if (post.Label.Trim().Length > 50) { post.Label = post.Label.Replace(",", ","); post.Label = post.Label.Trim().Substring(0, 50); } else { post.Label = post.Label.Replace(",", ","); } if (!post.IsWordDocument) { post.ResourceName = null; } if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase)) { post.ProtectContent = null; } post.Status = Status.Pended; post.PostDate = DateTime.Now; post.ModifyDate = DateTime.Now; Post p = post.Mapper <Post>(); if (!string.IsNullOrEmpty(Seminars)) { var tmp = Seminars.Split(',').Distinct(); tmp.ForEach(s => { var id = s.ToInt32(); p.Seminar.Add(SeminarBll.GetById(id)); }); } p.PostAccessRecord.Add(new PostAccessRecord() { AccessTime = DateTime.Today, ClickCount = 0 }); if (schedule) { if (timespan.HasValue && timespan.Value > DateTime.Now) { p.Status = Status.Schedule; HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p); return(ResultData(p.Mapper <PostOutputDto>(), message: schedule ? $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!" : "文章发表成功!")); } return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } p = PostBll.AddEntitySaved(p); if (p != null) { var cast = BroadcastBll.LoadEntities(c => c.Status == Status.Subscribed).ToList(); string link = Request.Url?.Scheme + "://" + Request.Url?.Authority + "/" + p.Id; cast.ForEach(c => { var ts = DateTime.Now.GetTotalMilliseconds(); string content = System.IO.File.ReadAllText(Request.MapPath("/template/broadcast.html")).Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.PostDate.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", post.Title).Replace("{{author}}", post.Author).Replace("{{content}}", post.Content.RemoveHtmlTag(150)).Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new { c.Email, act = "cancel", validate = c.ValidateCode, timespan = ts, hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(ConfigurationManager.AppSettings["BaiduAK"]) }, Request.Url.Scheme)); BackgroundJob.Schedule(() => SendMail(GetSettings("Title") + "博客有新文章发布了", content, c.Email), (p.PostDate - DateTime.Now)); }); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); return(ResultData(null, true, "文章发表成功!")); } return(ResultData(null, false, "文章发表失败!")); }
/// <summary> /// 刷新没统计到的访客的信息 /// </summary> public static void FlushAddress() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.FlushUnhandledAddress)); }
public static void AggregateInterviews() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.AggregateInterviews)); }
public Task Invoke(HttpContext context) { var request = context.Request; //启用读取request request.EnableBuffering(); if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP()) { context.Response.Redirect("https://www.baidu.com", true); //context.Response.StatusCode = 404; return(Task.CompletedTask); } var ip = context.Connection.RemoteIpAddress !.ToString(); var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8); var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path); var match = Regex.Match(path ?? "", CommonHelper.BanRegex); if (match.Length > 0) { RedisHelper.IncrBy("interceptCount"); RedisHelper.LPush("intercept", new IpIntercepter() { IP = ip, RequestUrl = requestUrl, Time = DateTime.Now, Referer = request.Headers[HeaderNames.Referer], UserAgent = request.Headers[HeaderNames.UserAgent], Remark = $"检测到敏感词拦截:{match.Value}", Address = request.Location(), HttpVersion = request.Protocol, Headers = request.Headers.ToJsonString() }); context.Response.StatusCode = 404; context.Response.ContentType = "text/html; charset=utf-8"; return(context.Response.WriteAsync("参数不合法!", Encoding.UTF8)); } if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot()) { context.Session.Set("session", 0); var referer = context.Request.Headers[HeaderNames.Referer].ToString(); if (!string.IsNullOrEmpty(referer)) { try { new Uri(referer);//判断是不是一个合法的referer if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" })) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: new dynamic[] { referer, ip }); } } catch { context.Response.StatusCode = 405; context.Response.ContentType = "text/html; charset=utf-8"; return(context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8)); } } } if (!context.Request.IsRobot()) { if (request.QueryString.HasValue && request.QueryString.Value.Contains("=")) { var q = request.QueryString.Value.Trim('?'); requestUrl = requestUrl.Replace(q, q.Split('&').Where(s => !s.StartsWith("cid") && !s.StartsWith("uid")).Join("&")); } TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog() { Count = 1, RequestUrls = { requestUrl }, UserAgents = { request.Headers[HeaderNames.UserAgent] } }, (_, i) => { i.UserAgents.Add(request.Headers[HeaderNames.UserAgent]); i.RequestUrls.Add(requestUrl); i.Count++; return(i); }); } if (string.IsNullOrEmpty(context.Session.Get <string>(SessionKey.TimeZone))) { context.Session.Set(SessionKey.TimeZone, context.Connection.RemoteIpAddress.GetClientTimeZone()); } if (!context.Request.Cookies.ContainsKey(SessionKey.RawIP)) { context.Response.Cookies.Append(SessionKey.RawIP, ip.Base64Encrypt(), new CookieOptions() { Expires = DateTimeOffset.Now.AddDays(1), SameSite = SameSiteMode.Lax }); } return(_next(context)); }
public async Task <ActionResult> Write(PostInputDto post, DateTime?timespan, bool schedule = false) { post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes()); if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available)) { return(ResultData(null, message: "请选择一个分类")); } if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null")) { post.Label = null; } else if (post.Label.Trim().Length > 50) { post.Label = post.Label.Replace(",", ","); post.Label = post.Label.Trim().Substring(0, 50); } else { post.Label = post.Label.Replace(",", ","); } if (!post.IsWordDocument) { post.ResourceName = null; } if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase)) { post.ProtectContent = null; } post.Status = Status.Pended; post.PostDate = DateTime.Now; post.ModifyDate = DateTime.Now; Post p = post.Mapper <Post>(); p.Modifier = p.Author; p.ModifierEmail = p.Email; p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); tmp.ForEach(s => { var id = s.ToInt32(); Seminar seminar = SeminarService.GetById(id); p.Seminar.Add(new SeminarPost() { Post = p, PostId = p.Id, Seminar = seminar, SeminarId = seminar.Id }); }); } if (schedule) { if (timespan.HasValue && timespan.Value > DateTime.Now) { p.Status = Status.Schedule; p.PostDate = timespan.Value; p.ModifyDate = timespan.Value; HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p); return(ResultData(p.Mapper <PostOutputDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!")); } return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } PostService.AddEntity(p); bool b = SearchEngine.SaveChanges() > 0; if (!b) { return(ResultData(null, false, "文章发表失败!")); } if ("true" == CommonHelper.SystemSettings["DisabledEmailBroadcast"]) { return(ResultData(null, true, "文章发表成功!")); } var cast = BroadcastService.GetQuery(c => c.Status == Status.Subscribed).ToList(); string link = Request.Scheme + "://" + Request.Host + "/" + p.Id; cast.ForEach(c => { var ts = DateTime.Now.GetTotalMilliseconds(); string content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/broadcast.html") .Replace("{{link}}", link + "?email=" + c.Email) .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss")) .Replace("{{title}}", post.Title).Replace("{{author}}", post.Author) .Replace("{{content}}", post.Content.RemoveHtmlTag(150)) .Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new { c.Email, act = "cancel", validate = c.ValidateCode, timespan = ts, hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(AppConfig.BaiduAK) }, Request.Scheme)); BackgroundJob.Schedule(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客有新文章发布了", content, c.Email), (p.ModifyDate - DateTime.Now)); }); return(ResultData(null, true, "文章发表成功!")); }
/// <summary> /// 每周任务 /// </summary> public static void EveryweekJob() { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), "default", new Random().Next(1, 10000)); }