Beispiel #1
3
        public ActionResult ArticleCreate(Article model)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files.Count != 1)
                {
                    ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
                    ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
                    return View();
                }
                var file = Request.Files[0];

                var s = new HtmlSanitizer();
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
                model.Image = Material.Create("", MaterialType.Avatar, file, db);
                model.NewArticle();
                db.Articles.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index", new { status = AdminOperationStatus.Success });
            }

            ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
            ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
            return View();
        }
Beispiel #2
1
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddBlazorModal();
     services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
     {
         var sanitizer = new Ganss.XSS.HtmlSanitizer();
         sanitizer.AllowedAttributes.Add("class");
         return(sanitizer);
     });
 }
        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
        {
            if (metadata.Model is string)
            {
                var sanitizer = new HtmlSanitizer(
                    allowedTags: _attribute != null ? _attribute.AllowedTags : new string[0],
                    allowedSchemes: new string[0],
                    allowedAttributes: new string[0],
                    uriAttributes: new string[0],
                    allowedCssProperties: new string[0]);

                var dirty = (string) metadata.Model;
                var sanitized = sanitizer.Sanitize(dirty, outputFormatter: OutputFormatters.HtmlEncodingNone);

                if (!dirty.Equals(sanitized))
                {
                    yield return new ModelValidationResult
                    {
                        MemberName = string.Empty,
                        Message = "A potentially dangerous value was detected from the client."
                    };
                }
            }
        }
Beispiel #4
0
 public static HtmlString HtmlDetails(this Ticket ticket)
 {
    
     var content = (ticket.IsHtml) ? ticket.Details : ticket.Details.HtmlFromMarkdown();
     var san = new HtmlSanitizer();
     return new HtmlString(san.Sanitize(content));
 }
        public string Sanitize(string html)
        {
            var sanitizer = new HtmlSanitizer();
            var result = sanitizer.Sanitize(html);

            return result;
        }
Beispiel #6
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddTransient(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Auth0", options.ProviderOptions);
                options.ProviderOptions.ResponseType = "code";
            });

            builder.Services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
            {
                // Configure sanitizer rules as needed here.
                // For now, just use default rules + allow class attributes
                var sanitizer = new Ganss.XSS.HtmlSanitizer();
                sanitizer.AllowedAttributes.Add("class");
                return(sanitizer);
            });

            //builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.Configuration["APIBaseAddress"])});
            builder.Services.AddScoped <ApiService>();
            builder.Services.AddHttpClient <ApiService>(hc => hc.BaseAddress = new Uri(builder.Configuration["APIBaseAddress"]))
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetRetryPolicy());

            await builder.Build().RunAsync();
        }
Beispiel #7
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddBlazoredLocalStorage();
     services.AddTransient <IAppVersionService, AppVersionService>();
     services.AddAuthorizationCore();
     services.AddScoped <AuthenticationStateProvider, ApiAuthenticationStateProvider>();
     services.AddScoped <IAuthService, AuthService>();
     services.AddFileReaderService(options => options.UseWasmSharedBuffer = true);
     services.AddMatToaster(config =>
     {
         config.Position          = MatToastPosition.BottomRight;
         config.PreventDuplicates = true;
         config.NewestOnTop       = true;
         config.ShowCloseButton   = true;
         config.MaximumOpacity    = 93;
         //config.VisibleStateDuration = 7000;
     });
     services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
     {
         // Configure sanitizer rules as needed here.
         // For now, just use default rules + allow class attributes
         var sanitizer = new Ganss.XSS.HtmlSanitizer();
         sanitizer.AllowedAttributes.Add("class");
         return(sanitizer);
     });
 }
        public void IsValidHtml(
            string html,
            out string sanitizedHtml,
            out bool wasModified,
            ISet<string> allowedTags = null,
            ISet<string> allowedUrlSchemes = null,
            ISet<string> allowedAttributes = null,
            ISet<string> allowedUriAttributes = null,
            ISet<string> allowedCssProperties = null,
            bool appendAllowedToDefaults = true)
        {
            if (appendAllowedToDefaults)
            {
                allowedTags?.AddRange(this.DefaultAllowedTags);
                allowedUrlSchemes?.AddRange(this.DefaultUrlSchemes);
                allowedAttributes?.AddRange(this.DefaultAttributes);
                allowedUriAttributes?.AddRange(this.DefaultUrlAttributes);
                allowedCssProperties?.AddRange(this.DefaultAllowedCssProperties);
            }

            var sanitizer = new HtmlSanitizer(
                allowedTags,
                allowedUrlSchemes,
                allowedAttributes,
                allowedUriAttributes,
                allowedCssProperties);

            sanitizedHtml = sanitizer.Sanitize(html);

            wasModified = html != sanitizedHtml;
        }
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddScoped <Auth0AuthorizationMessageHandler>();
            ;
            var baseAddress = builder.Configuration["HttpClientBaseAddress"];

            builder.Services.AddHttpClient <ProjectApiService>(sp => sp.BaseAddress = new Uri(baseAddress))
            .AddHttpMessageHandler <Auth0AuthorizationMessageHandler>()
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetRetryPolicy());
            builder.Services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
            {
                // Configure sanitizer rules as needed here.
                // For now, just use default rules + allow class attributes
                var sanitizer = new Ganss.XSS.HtmlSanitizer();
                sanitizer.AllowedAttributes.Add("class");
                return(sanitizer);
            });
            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Auth0", options.ProviderOptions);
                options.ProviderOptions.ResponseType = "code";
                options.ProviderOptions.DefaultScopes.Add("https://schemas.dev-f6kthe8k.com/roles");
            });

            await builder.Build().RunAsync();
        }
        public static string Sanitize(string html)
        {
            var sanitizer = new HtmlSanitizer();
            sanitizer.AllowedAttributes.Add("class");
            var sanitizedHtml = sanitizer.Sanitize(html);

            return sanitizedHtml;
        }
        public static HtmlString HtmlComment(this TicketEvent ticketEvent)
        {
            var content = (ticketEvent.IsHtml) ? ticketEvent.Comment : ticketEvent.Comment.HtmlFromMarkdown();
            var san = new HtmlSanitizer();

            return new HtmlString(san.Sanitize(content));
            
        }
Beispiel #12
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
     {
         // Configure sanitizer rules as needed here.
         // For now, just use default rules + allow class attributes
         var sanitizer = new Ganss.XSS.HtmlSanitizer();
         sanitizer.AllowedAttributes.Add("class");
         return(sanitizer);
     });
 }
Beispiel #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();

            // used in MarkdownViewer for markup/down conversion
            services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(p => {
                var sanitizer = new Ganss.XSS.HtmlSanitizer(); // start with the defaults
                sanitizer.AllowedTags.Add("p");                // add <p>
                return(sanitizer);
            });
        }
        /// <summary>
        /// Add Markdown services.
        /// </summary>
        /// <param name="services"></param>
        public static void AddMarkdownServices(this IServiceCollection services)
        {
            services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
            {
                // Configure sanitizer rules as needed here.
                // For now, just use default rules + allow class attributes
                var sanitizer = new Ganss.XSS.HtmlSanitizer();
                sanitizer.AllowedAttributes.Add("class");
                return(sanitizer);
            });

            services.AddSingleton <Highlight>();
        }
Beispiel #15
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddHttpClient <ProjectApiService>(hc => hc.BaseAddress = new Uri(builder.Configuration["APIBaseAddress"]))
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetRetryPolicy());

            builder.Services.AddScoped <Auth0AuthorizationMessageHandler>();
            builder.Services.AddScoped <ProjectApiService>();
            builder.Services.AddHttpClient <ProjectApiService>(hc => hc.BaseAddress = new Uri(builder.Configuration["APIBaseAddress"]))
            .AddHttpMessageHandler <Auth0AuthorizationMessageHandler>()
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetRetryPolicy());

            builder.Services.AddTransient(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Auth0", options.ProviderOptions);
                options.ProviderOptions.ResponseType = "code";
                options.ProviderOptions.DefaultScopes.Add("https://schemas.dev-01xt5ns9.com/roles");
            });

            builder.Services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
            {
                // Configure sanitizer rules as needed here.
                // For now, just use default rules + allow class attributes
                var sanitizer = new Ganss.XSS.HtmlSanitizer();
                sanitizer.AllowedAttributes.Add("class");
                return(sanitizer);
            });
            builder.Services.Configure <RouteOptions>(options =>
            {
                options.ConstraintMap.Add("slug", typeof(SlugParameterTransformer));
            });

            await builder.Build().RunAsync();
        }
        public ActionResult ArticleCreate(Article model)
        {
            var s = new HtmlSanitizer();
            if (ModelState.IsValid)
            {
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
                var file = Request.Files[0];
                if (Request.Files.Count >= 1 && file.FileName != "")
                {
                    if (MaterialType.Avatar.Match(file))
                    {
                        model.Image = Material.Create("", MaterialType.Avatar, Request.Files[0], db);
                        if (model.Image == null)
                        {
                            ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
                            ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
                            return View(model);
                        }
                    }
                    else
                    {
                        ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
                        ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
                        TempData["Alert"] = "请检查上传文件的格式是否正确!";
                        return View(model);
                    }
                }
                else
                {
                    model.Image = db.Materials.Find(Guid.Empty.DefaultMaterial(DefaultMaterial.News));
                }
                model.NewArticle();
                db.Articles.Add(model);
                db.SaveChanges();
                TempData["Alert"] = "文章创建成功!";
                return RedirectToAction("Articles");
            }

            model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
            ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
            ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
            return View();
        }
Beispiel #17
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Auth0", options.ProviderOptions);
                options.ProviderOptions.ResponseType = "code";
                options.ProviderOptions.DefaultScopes.Add("https://schemas.marceloZometa.com/roles");
            });

            builder.Services.AddScoped <Auth0AuthorizationMessageHandler>();

            builder.Services.AddHttpClient <APIService>(hc => hc.BaseAddress = new Uri(builder.Configuration["APIBaseAddress"]))
            .AddHttpMessageHandler <Auth0AuthorizationMessageHandler>()
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetPolicy());

            //builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
            //.CreateClient("APIService"));

            builder.Services.AddHttpClient <PublicAPIService>(hc => hc.BaseAddress = new Uri(builder.Configuration["APIBaseAddress"]))
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetPolicy());
            //builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });



            builder.Services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(x =>
            {
                var sanitizer = new Ganss.XSS.HtmlSanitizer();
                sanitizer.AllowedAttributes.Add("class");
                return(sanitizer);
            });

            await builder.Build().RunAsync();
        }
        public ActionResult Edit(RoomOperation roomOperation)
        {
            if (ModelState.IsValid && roomOperation != null)
            {
                var s = new HtmlSanitizer();
                roomOperation.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"])); ;
                if (roomOperation.StartTime >= roomOperation.EndTime)
                {
                    TempData["Alert"] = "无法完成修改,开始时间晚于结束时间。";
                    return View();
                }
                if (roomOperation.Edit())
                {
                    var user = Extensions.GetContextUser(ref db);
                    var RoomRecords = roomOperation.RoomRecords;
                    if (RoomRecords != null)
                    {
                        var lastRecord = RoomRecords.Where(r => r.ActionTime.AddDays(7.0) > r.RoomOperation.StartTime);
                        if (RoomRecords != null && lastRecord != null)
                        {
                            string title = "场地修改通知";
                            string content = "您好,你选择的场地[" + roomOperation.Name + "]已被修改,请及时查看相关信息,并根据新的场地信息安排你的日程";
                            Message message = new Message(title, content, lastRecord.First().Receiver.Id, MessageType.System, db);
                            if (message.Publish())
                            {
                                return RedirectToAction("Index");
                            }
                            TempData["Alert"] = "无法给学生发布修改信息";
                        }
                    }
                }
                else
                    TempData["Alert"] = "修改失败!";
            }
            else
                TempData["Alert"] = "无法修改!对象不存在或无效。";

            return RedirectToAction("Index");
        }
Beispiel #19
0
 public string Sanitize(string html)
 {
     var sanitizer = new HtmlSanitizer();
     return sanitizer.Sanitize(html);
 }
 private string SanitizeHtmlSanitizer(string dirty, AllowHtmlAttribute attribute)
 {
     var sanitizer = new HtmlSanitizer(
         allowedTags: attribute != null ? attribute.AllowedTags : new string[0],
         allowedSchemes: new string[0],
         allowedAttributes: new string[0],
         uriAttributes: new string[0],
         allowedCssProperties: new string[0]);
     return sanitizer.Sanitize(dirty, outputFormatter: OutputFormatters.HtmlEncodingNone);
 }
 public HtmlSecuritySanitizer()
 {
     this.sanitizer = new HtmlSanitizer();
 }
        public ActionResult ActivityEdit(ActivityOperation model)
        {
            var s = new HtmlSanitizer();
            if (ModelState.IsValid)
            {
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"])); ;
                db.ActivityOperations.Attach(model);
                db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", new { status = AdminOperationStatus.Success });
            }

            model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
            return View(model);
        }
 public ActionResult EditPost(int? id, int? account_id, string val)
 {
     if (Session["User"] == null || id == null || account_id == null || account_id != Convert.ToInt32(Session["User"]))
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     else
     {
         Account a = db.Accounts.Find(Session["User"]);
         Post p = db.Posts.Find(id);
         if (a != null && (Session["Elevation"].Equals("Administrator") || p.id == id))
         {
             if (p != null)
             {
                 var sanitizer = new HtmlSanitizer();
                 string sanitized = sanitizer.Sanitize(val);
                 p.entry = HttpUtility.HtmlEncode(sanitized);
                 p.editor_id = a.id;
                 db.SaveChanges();
                 return new HttpStatusCodeResult(HttpStatusCode.OK);
             }
             else
             {
                 return HttpNotFound();
             }
         }
         else
         {
             return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
     }
 }
        public ActionResult ArticleEdit(Article model)
        {
            var s = new HtmlSanitizer();
            if (ModelState.IsValid)
            {
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
                db.Articles.Attach(model);
                db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                TempData["Alert"] = "文章编辑成功!";
                return RedirectToAction("Articles");
            }

            model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
            ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
            ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
            return View(model);
        }
Beispiel #25
0
        /// <summary>
        /// Sanitizes an HTML string.
        /// </summary>
        public string SanitizeHtml(string html)
        {
            var sanitizer = new Ganss.XSS.HtmlSanitizer();

            return(sanitizer.Sanitize(html));
        }
        public ActionResult Post(NewPostViewModel npvm)
        {
            if (Session["User"] == null)
            {
                return RedirectToAction("LoginPage", "Application");
            }
            else if (npvm.id != Convert.ToInt32(Session["User"]))
            {
                return RedirectToAction("LoggedInProfile");
            }
            else if (this.ModelState.IsValid)
            {
                Post p = new Post();
                Account a = db.Accounts.Find(Session["User"]);

                if (a == null)
                {
                    return RedirectToAction("LoginPage", "Application");
                }
                else
                {
                    p.account_id = a.id;
                    var sanitizer = new HtmlSanitizer();
                    if (npvm.entry == null)
                    {
                        npvm.entry = "";
                    }
                    string sanitized = sanitizer.Sanitize(npvm.entry);
                    p.entry = HttpUtility.HtmlEncode(sanitized);
                    p.date_posted = DateTime.Now;
                    foreach(LinkedItemViewModel livm in npvm.linked_items.Where(x => x.isChecked == true).ToList())
                    {
                        LinkedItem li = new LinkedItem();
                        li.item_id = livm.id;
                        li.post_id = p.id;
                        db.LinkedItems.Add(li);
                    }
                    db.Posts.Add(p);
                    db.SaveChanges();
                    return RedirectToAction("Boards", "Application");
                }
            }
            else
            {
                return RedirectToAction("Boards", "Application");
            }
        }
Beispiel #27
0
 public static string Sanitize(this string input)
 {
     var htmlSanitizer = new HtmlSanitizer();
     var sanitizedHtml = htmlSanitizer.Sanitize(input);
     return sanitizedHtml;
 }
Beispiel #28
0
        public ActionResult ArticleEdit(Article model)
        {
            if (ModelState.IsValid)
            {
                var s = new HtmlSanitizer();
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"])); ;
                db.Articles.Attach(model);
                db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", new { status = AdminOperationStatus.Success });
            }

            ViewData["StatusList"] = EnumExtension.GetSelectList(typeof(ArticleStatus));
            ViewData["ClassList"] = EnumExtension.GetSelectList(typeof(ArticleClass));
            return View();
        }
        public ActionResult ActivityCreate(ActivityOperation model)
        {
            var s = new HtmlSanitizer();
            if (ModelState.IsValid)
            {
                if (model.StartTime > model.EndTime)
                {
                    ViewData["Alert"] = "活动开始时间必须在结束时间之前。";
                    model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
                    return View(model);
                }
                model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
                model.NewActivity(db);
                db.ActivityOperations.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index", new { status = AdminOperationStatus.Success });
            }

            model.Content = Server.HtmlDecode(s.Sanitize(Request.Params["ck"]));
            return View(model);
        }
Beispiel #30
0
 public void TestSanitizeSafeString()
 {
     var sanitizer = new HtmlSanitizer();
     const string safe = "<i>hello</i> there";
     Assert.AreEqual(safe, sanitizer.Sanitize(safe));
 }
Beispiel #31
0
		private async Task AddAuctionToDatabase(Auction newAuction)
		{
			var sanitizer = new HtmlSanitizer();
			
			newAuction.Description = sanitizer.Sanitize(newAuction.Description);

			await InsertAuction(newAuction);
		}