public ActionResult Details(int id, string kw) { var post = PostService.Get(p => p.Id == id && (p.Status == Status.Pended || 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.Pended || CurrentUser.IsAdmin), p => p.ModifyDate); ViewBag.Prev = PostService.GetFromCache <DateTime, PostModelBase>(p => p.ModifyDate < modifyDate && (p.Status == Status.Pended || CurrentUser.IsAdmin), p => p.ModifyDate, false); if (!string.IsNullOrEmpty(kw)) { ViewData["keywords"] = post.Content.Contains(kw) ? $"['{kw}']" : SearchEngine.LuceneIndexSearcher.CutKeywords(kw).ToJsonString(); } 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)); }
public ActionResult Details(int id, string kw) { Post post = PostBll.GetById(id); if (post != null) { ViewBag.Keyword = post.Keyword + "," + post.Label; UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto(); DateTime modifyDate = post.ModifyDate; ViewBag.Next = PostBll.GetFirstEntityFromL2CacheNoTracking(p => p.ModifyDate > modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate); ViewBag.Prev = PostBll.GetFirstEntityFromL2CacheNoTracking(p => p.ModifyDate < modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate, false); if (user.IsAdmin) { return(View("Details_Admin", post)); } if (post.Status != Status.Pended) { return(RedirectToAction("Post", "Home")); } if (string.IsNullOrEmpty(Session.GetByRedis <string>("post" + id))) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id); Session.SetByRedis("post" + id, id.ToString()); } return(View(post)); } return(RedirectToAction("Index", "Error")); }
/// <summary> /// 登录页 /// </summary> /// <returns></returns> public ActionResult Login() { var keys = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS1); Response.Cookies.Append(nameof(keys.PublicKey), keys.PublicKey, new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Set(nameof(keys.PrivateKey), keys.PrivateKey); string from = Request.Query["from"]; if (!string.IsNullOrEmpty(from)) { from = HttpUtility.UrlDecode(from); Response.Cookies.Append("refer", from, new CookieOptions() { SameSite = SameSiteMode.Lax }); } if (HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo) != null) { if (string.IsNullOrEmpty(from)) { return(RedirectToAction("Index", "Home")); } return(LocalRedirect(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.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); 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(LocalRedirect(from)); } } return(View()); }
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); ViewBag.Related = related; 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)); }
public IActionResult Authenticate(AuthenticateModel model) { var user = UserInfoService.Login(model.Username, model.Password); if (user is null) { return(BadRequest(new ErrorResponse() { message = "错误的用户名或密码" })); } Response.Cookies.Append("username", HttpUtility.UrlEncode(model.Username.Trim()), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", model.Password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); HttpContext.Session.Set(SessionKey.UserInfo, user); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", user, HttpContext.Connection.RemoteIpAddress.ToString(), LoginType.Default); return(Ok(new { error = false, id = model.Username, username = model.Username, token = model.Username })); }
public ActionResult Pass(int id) { Post post = PostBll.GetById(id); post.Status = Status.Pended; post.ModifyDate = DateTime.Now; post.PostDate = DateTime.Now; bool b = PostBll.UpdateEntitySaved(post); var cast = BroadcastBll.LoadEntities(c => c.Status == Status.Subscribed).ToList(); string link = Request.Url?.Scheme + "://" + Request.Url?.Authority + "/" + 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.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(ConfigurationManager.AppSettings["BaiduAK"]) }, Request.Url.Scheme)); BackgroundJob.Enqueue(() => SendMail(GetSettings("Title") + "博客有新文章发布了", content, c.Email)); }); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); return(ResultData(null, b, b ? "审核通过!" : "审核失败!")); }
public ActionResult Login(string username, string password, string valid, string remem) { string validSession = HttpContext.Session.GetByRedis <string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较 if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return(ResultData(null, false, "验证码错误")); } HttpContext.Session.RemoveByRedis("valid"); //验证成功就销毁验证码Session,非常重要 if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim())) { return(ResultData(null, false, "用户名或密码不能为空")); } var userInfo = UserInfoService.Login(username, password); if (userInfo != null) { HttpContext.Session.SetByRedis(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, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default); string refer = Request.Cookies["refer"]; return(ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer)); } return(ResultData(null, false, "用户名或密码错误")); }
public static (BackgroundJobServer server, IRecurringJobManager recurringJobManager, IBackgroundJobClient backgroundJobClient) StartHangfireServer( string tenantId, string serverName, string connectionString, IApplicationLifetime applicationLifetime, IJobFilterProvider jobFilters, MultitenantContainer mtc, IBackgroundJobFactory backgroundJobFactory, IBackgroundJobPerformer backgroundJobPerformer, IBackgroundJobStateChanger backgroundJobStateChanger, IBackgroundProcess[] additionalProcesses ) { var tenantJobActivator = new AspNetCoreMultiTenantJobActivator(mtc, tenantId); return(HangfireHelper.StartHangfireServer( serverName, connectionString, applicationLifetime, jobFilters, tenantJobActivator, backgroundJobFactory, backgroundJobPerformer, backgroundJobStateChanger, additionalProcesses)); }
public async Task Invoke(HttpContext context) { if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot()) { context.Session.Set("session", 0); CommonHelper.InterviewCount++; 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 { await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8); return; } } } await _next.Invoke(context); }
/// <summary> /// hangfire初始化 /// </summary> public static void Start() { RecurringJob.AddOrUpdate(() => CheckLinks(), "0 */5 * * *"); //每5h检查友链 RecurringJob.AddOrUpdate(() => EverydayJob(), Cron.Daily(5), TimeZoneInfo.Local); //每天的任务 RecurringJob.AddOrUpdate(() => EveryweekJob(), Cron.Weekly(DayOfWeek.Monday, 5), TimeZoneInfo.Local); //每周的任务 RecurringJob.AddOrUpdate(() => EveryHourJob(), Cron.Hourly); //每小时的任务 BackgroundJob.Enqueue(() => HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.StatisticsSearchKeywords), "default")); }
public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false) { post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes()); if (!ValidatePost(post, out var resultData)) { return(resultData); } 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.ToUniversalTime(); p.ModifyDate = timespan.Value.ToUniversalTime(); 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 Login([FromServices] ICacheManager <int> cacheManager, 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, "用户名或密码不能为空")); } password = password.RSADecrypt(HttpContext.Session.Get <string>(nameof(RsaKey.PrivateKey))); var userInfo = UserInfoService.Login(username, password); if (userInfo == null) { var times = cacheManager.AddOrUpdate("LoginError:" + ClientIP, 1, i => i + 1, 5); if (times > 30) { FirewallRepoter.ReportAsync(IPAddress.Parse(ClientIP)).ContinueWith(_ => LogManager.Info($"多次登录用户名或密码错误,疑似爆破行为,已上报IP{ClientIP}至:" + FirewallRepoter.ReporterName)); } 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.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); } HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default); string refer = Request.Cookies["refer"]; Response.Cookies.Delete(nameof(RsaKey.PublicKey), new CookieOptions() { SameSite = SameSiteMode.Lax }); Response.Cookies.Delete("refer", new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Remove(nameof(RsaKey.PrivateKey)); return(ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer)); }
public async Task Invoke(HttpContext context) { var request = context.Request; if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP()) { return; } 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 = context.Connection.RemoteIpAddress.ToString(), 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; } } } TrackData.RequestLogs.AddOrUpdate(requestUrl, 1, (s, i) => i + 1); await _next.Invoke(context); }
public bool Authorize([NotNull] DashboardContext context) { var httpContext = context.GetHttpContext(); var options = httpContext.RequestServices.GetService <IOptions <ElectHangfireOptions> >().Value; var isCanAccess = HangfireHelper.IsCanAccessHangfireDashboard(httpContext, options); return(isCanAccess); }
public ActionResult Restore(int id) { var post = PostBll.GetById(id); post.Status = Status.Pended; bool b = PostBll.UpdateEntitySaved(post); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); return(ResultData(null, b, b ? "恢复成功!" : "恢复失败!")); }
public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false, CancellationToken cancellationToken = default) { post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken); if (!ValidatePost(post, out var resultData)) { return(resultData); } post.Status = Status.Published; Post p = post.Mapper <Post>(); p.Modifier = p.Author; p.ModifierEmail = p.Email; p.IP = ClientIP; p.Rss = p.LimitMode is null or RegionLimitMode.All; 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(seminar); } } if (schedule) { if (!timespan.HasValue || timespan.Value <= DateTime.Now) { return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } p.Status = Status.Schedule; p.PostDate = timespan.Value.ToUniversalTime(); p.ModifyDate = timespan.Value.ToUniversalTime(); 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); var js = new JiebaSegmenter(); (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s)); bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章发表失败!")); } return(ResultData(null, true, "文章发表成功!")); }
/// <summary>在执行操作方法之前由 ASP.NET MVC 框架调用。</summary> /// <param name="filterContext">筛选器上下文。</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var req = filterContext.HttpContext.Request; try { if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorityAttribute), true).Length <= 0 && req.HttpMethod.Equals("GET", StringComparison.InvariantCultureIgnoreCase) && req.UserAgent != null && !req.UserAgent.Contains(new[] { "DNSPod", "Baidu", "spider", "Python", "bot" })) { Guid uid = filterContext.HttpContext.Session.Get <Guid>("currentOnline"); if (uid == Guid.Empty) { uid = Guid.NewGuid(); filterContext.HttpContext.Session.Set("currentOnline", uid); } HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.InterviewTrace), null, uid, req.Url.ToString().Replace(":80/", "/")); } } catch { // ignored } #region 禁用浏览器缓存 filterContext.HttpContext.Response.Headers.Add("Pragma", "no-cache"); filterContext.HttpContext.Response.Headers.Add("Expires", "0"); filterContext.HttpContext.Response.Buffer = true; filterContext.HttpContext.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1); filterContext.HttpContext.Response.Expires = 0; filterContext.HttpContext.Response.CacheControl = "no-cache"; filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); filterContext.HttpContext.Response.Cache.SetNoStore(); #endregion #region 启用ETag filterContext.HttpContext.Response.Filter = new ETagFilter(filterContext.HttpContext.Response, filterContext.RequestContext.HttpContext.Request); #endregion #region 压缩HTML if (EnableViewCompress) { _sb = new StringBuilder(); _sw = new StringWriter(_sb); _tw = new HtmlTextWriter(_sw); _output = filterContext.RequestContext.HttpContext.Response.Output as HttpWriter; filterContext.RequestContext.HttpContext.Response.Output = _tw; } #endregion }
/// <summary> /// 启动后执行的入口 /// </summary> public void Invoke() { // 当数据库为sqlite时,hangfire会执行多次invoke,暂不清楚是什么原因,故加上锁 lock (_locker) { // 增加定时任务 HangfireHelper.AddHangfire(new Assembly[] { typeof(Startup).Assembly, typeof(ServiceContext).Assembly }); // 初始化数据库 InitDatabase(); } }
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, "用户名或密码不能为空")); } password = password.RSADecrypt(HttpContext.Session.Get <string>(nameof(RsaKey.PrivateKey))); 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.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); } HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default); string refer = Request.Cookies["refer"]; Response.Cookies.Delete(nameof(RsaKey.PublicKey), new CookieOptions() { SameSite = SameSiteMode.Lax }); Response.Cookies.Delete("refer", new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Remove(nameof(RsaKey.PrivateKey)); return(ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseHangfireDashboard(); app.UseHangfireServer(); HangfireHelper.SetupRecurringJobs(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseHangfireDashboard("", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationHack() } }); app.UseHangfireServer(); HangfireHelper.RegisterJobs(app.ApplicationServices.GetService <IServiceScopeFactory>()); }
public async Task <ActionResult> Details(int id, string kw, int cid, string t) { var notRobot = !Request.IsRobot(); if (string.IsNullOrEmpty(t) && notRobot) { return(RedirectToAction("Details", cid > 0 ? new { id, kw, cid, t = SnowFlake.NewId } : new { id, kw, t = SnowFlake.NewId })); } var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到"); CheckPermission(post); ViewBag.Keyword = post.Keyword + "," + post.Label; ViewBag.Desc = await post.Content.GetSummary(200); var modifyDate = post.ModifyDate; ViewBag.Next = await PostService.GetFromCacheAsync <DateTime, PostModelBase>(p => p.ModifyDate > modifyDate && (p.LimitMode ?? 0) == RegionLimitMode.All && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate); ViewBag.Prev = await PostService.GetFromCacheAsync <DateTime, PostModelBase>(p => p.ModifyDate < modifyDate && (p.LimitMode ?? 0) == RegionLimitMode.All && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate, false); if (!string.IsNullOrEmpty(kw)) { await PostService.Highlight(post, kw); } ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId); var regex = SearchEngine.LuceneIndexSearcher.CutKeywords(string.IsNullOrWhiteSpace(post.Keyword + post.Label) ? post.Title : post.Keyword + post.Label).Select(Regex.Escape).Join("|"); var related = await PostService.GetQuery(PostBaseWhere().And(p => p.Id != id && Regex.IsMatch(p.Title + (p.Keyword ?? "") + (p.Label ?? ""), regex)), p => p.AverageViewCount, false).Take(10).Select(p => new { p.Id, p.Title }).Cacheable().ToDictionaryAsync(p => p.Id, p => p.Title); 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)); post.Content = ReplaceVariables(post.Content); post.ProtectContent = ReplaceVariables(post.ProtectContent); if (CurrentUser.IsAdmin) { return(View("Details_Admin", post)); } if (notRobot && string.IsNullOrEmpty(HttpContext.Session.Get <string>("post" + id))) { HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: new dynamic[] { id, ClientIP, Request.Headers[HeaderNames.Referer].ToString(), HttpUtility.UrlDecode(Request.Scheme + "://" + Request.Host + Request.Path + Request.QueryString) }); HttpContext.Session.Set("post" + id, id.ToString()); } return(View(post)); }
public async Task Invoke(HttpContext context) { var request = context.Request; var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8); if (Regex.Match(path ?? "", CommonHelper.BanRegex).Length > 0) { BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter() { IP = context.Connection.RemoteIpAddress.MapToIPv4().ToString(), RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path), Time = DateTime.Now, UserAgent = request.Headers[HeaderNames.UserAgent] })); context.Response.StatusCode = 504; await context.Response.WriteAsync("参数不合法!", Encoding.UTF8); return; } if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot()) { context.Session.Set("session", 0); CommonHelper.InterviewCount++; 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; } } } await _next.Invoke(context); }
public ActionResult Login(string username, string password, string valid, string remem) { string validSession = Session.GetByCookieRedis <string>("valid") ?? String.Empty; //将验证码从Session中取出来,用于登录验证比较 if (String.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return(ResultData(null, false, "验证码错误")); } Session.RemoveByCookieRedis("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(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); } #if !DEBUG HangfireHelper.CreateJob(typeof(IHangfireBackJob), "LoginRecord", "default", userInfo, Request.UserHostAddress); #endif string refer = CookieHelper.GetCookieValue("refer"); if (string.IsNullOrEmpty(refer)) { return(ResultData(null, true, "/")); } return(ResultData(null, true, refer)); } return(ResultData(null, false, "用户名或密码错误")); }
public JsonResult RefreshToken(OAuth2Result model) { try { // 删除日志 HangfireHelper.StartHanfireWork(); var clientId = model.ClientId; var clientSecret = model.ClientSecret; var refreshToken = ScryptHelper.DecryptDES(model.RefreshToken); var basic = Convert.ToBase64String(Encoding.Default.GetBytes($"{clientId}:{clientSecret}")); string resStr = string.Empty; var handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = delegate { return(true); }; using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + basic); var json = $"grant_type=refresh_token&refresh_token={refreshToken}"; var content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded"); var res = httpClient.PostAsync($"{Constant.OAuth2Url}/oauth2/token", content).Result; resStr = res.Content.ReadAsStringAsync().Result; _log.Debug($"RefreshToken oauth2 token: '{resStr}'"); } var obj = JsonConvert.DeserializeObject <dynamic>(resStr); OAuth2Result result = new OAuth2Result() { AccessToken = ScryptHelper.EncryptDES($"Bearer {obj["access_token"].Value}"), ExpireIn = DateTime.Now.AddSeconds(obj["expires_in"].Value), IdToken = obj["id_token"].Value, RefreshToken = ScryptHelper.EncryptDES(obj["refresh_token"].Value), ClientId = model.ClientId, ClientSecret = model.ClientSecret }; return(Json(new { success = true, token = JsonConvert.SerializeObject(result) })); } catch (Exception ex) { _log.Debug($"RefreshToken Parameter: {JsonConvert.SerializeObject(model)}, Exception: {ex.Message}"); return(Json(new { success = false })); } }
/// <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.GetByRedis <UserInfoOutputDto>(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.SetByRedis(SessionKey.UserInfo, userInfo); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default); if (string.IsNullOrEmpty(from)) { return(RedirectToAction("Index", "Home")); } return(Redirect(from)); } } return(View()); }
public ActionResult Truncate(int id) { var post = PostBll.GetById(id); if (post is null) { return(ResultData(null, false, "文章已经被删除!")); } if (post.IsWordDocument) { try { System.IO.File.Delete(Path.Combine(Server.MapPath("/upload"), post.ResourceName)); Directory.Delete(Path.Combine(Server.MapPath("/upload"), Path.GetFileNameWithoutExtension(post.ResourceName)), true); } catch (IOException) { } } var mc = post.Content.MatchImgTags(); foreach (Match m in mc) { string path = m.Groups[3].Value; if (path.StartsWith("/")) { path = Path.Combine(Server.MapPath("/"), path); try { System.IO.File.Delete(path); } catch (IOException) { } } } bool b = PostBll.DeleteByIdSaved(id); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); return(ResultData(null, b, b ? "删除成功!" : "删除失败!")); }
private static void ListenForNewUsers(object source, EntryWrittenEventArgs e) { if ((ushort)e.Entry.InstanceId != 4720) { return; } LogHelper.Logger.Info($"New Event - Instance {e.Entry.InstanceId} Type {e.Entry.EntryType} Source {e.Entry.Source}"); EventLogEntry entry = e.Entry; // sometimes it reschedules the jobs straight away. // make sure they are cancelled! LogHelper.Logger.Info("Event triggered - Cancelling any running jobs"); HangfireHelper.CancelAllJobs(); Thread.Sleep(10000); HangfireHelper.CancelAllJobs(); EventBus.Default.Trigger(new NewActiveDirectoryUserEventData(entry)); }
/// <summary> /// 登录页 /// </summary> /// <returns></returns> public ActionResult Login() { string from = Request["ReturnUrl"]; if (!string.IsNullOrEmpty(from)) { from = Server.UrlDecode(from); CookieHelper.SetCookie("refer", from); } if (Session.GetByCookieRedis <UserInfoDto>() != 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(userInfo); HangfireHelper.CreateJob(typeof(IHangfireBackJob), "LoginRecord", "default", userInfo, Request.UserHostAddress); if (string.IsNullOrEmpty(from)) { return(RedirectToAction("Index", "Home")); } return(Redirect(from)); } } return(View()); }
public static void Register() { #region Hangfire配置 //GlobalConfiguration.Configuration.UseMemoryStorage(); GlobalConfiguration.Configuration.UseSqlServerStorage(ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString).UseConsole(); #region 实现类注册 GlobalConfiguration.Configuration.UseAutofacActivator(AutofacConfig.Container); #endregion #region 务启动 Server = new BackgroundJobServer(new BackgroundJobServerOptions { ServerName = $"{Environment.MachineName}", //服务器名称 SchedulePollingInterval = TimeSpan.FromSeconds(1), ServerCheckInterval = TimeSpan.FromSeconds(1), WorkerCount = Environment.ProcessorCount * 2, //Queues = new[] { "masuit" } //队列名 }); #endregion #endregion HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); //更新文章索引 AggregateInterviews(); //访客统计 RecurringJob.AddOrUpdate(() => Windows.ClearMemorySilent(), Cron.Hourly); //每小时清理系统内存 RecurringJob.AddOrUpdate(() => CheckLinks(), Cron.HourInterval(5)); //每5h检查友链 RecurringJob.AddOrUpdate(() => EverydayJob(), Cron.Daily, TimeZoneInfo.Local); //每天的任务 RecurringJob.AddOrUpdate(() => AggregateInterviews(), Cron.Hourly(30)); //每半小时统计访客 using (RedisHelper redisHelper = RedisHelper.GetInstance()) { if (!redisHelper.KeyExists("ArticleViewToken")) { redisHelper.SetString("ArticleViewToken", string.Empty.CreateShortToken()); //更新加密文章的密码 } } }