This commit is contained in:
Alexander
2023-11-25 17:11:04 +03:00
parent 77c602cd9c
commit 73e6e4d3b1
13 changed files with 328 additions and 23 deletions

View File

@@ -0,0 +1,122 @@
using anbs_cp.ForNet.Enums;
using Ganss.Xss;
namespace anbs_cp.ForNet.Classes;
/// <summary>
/// Очистка текста от лишних HTML-тегов
/// </summary>
public static class Sanitizer
{
/// <summary>
/// Очистка текста по уровню очистки
/// </summary>
/// <param name="html">Текст</param>
/// <param name="level">Уровень очистка</param>
/// <returns>Очищенный текст</returns>
public static string SanitizeHtml (string html, ESanitizerLevel level)
{
HtmlSanitizer sanitizer = new()
{
KeepChildNodes = true
};
switch (level)
{
case ESanitizerLevel.NoTags:
PrepareForNone(ref sanitizer);
break;
case ESanitizerLevel.TextFormatOnly:
PrepareForTextFormatOnly(ref sanitizer);
break;
case ESanitizerLevel.ImageAndLinks:
PrepareForImageAndLinks(ref sanitizer);
break;
case ESanitizerLevel.AllExceptIFrame:
PrepareForAllExceptIFrame(ref sanitizer);
break;
default:
PrepareForNone(ref sanitizer);
break;
}
return level != ESanitizerLevel.All ? sanitizer.Sanitize(html) : html;
}
/// <summary>
/// Очистка всех тегов
/// </summary>
/// <param name="sanitizer"><see cref="HtmlSanitizer"/></param>
private static void PrepareForNone (ref HtmlSanitizer sanitizer)
{
sanitizer.AllowedTags.Clear();
sanitizer.AllowedSchemes.Clear();
sanitizer.AllowedCssProperties.Clear();
sanitizer.AllowedClasses.Clear();
sanitizer.AllowedAttributes.Clear();
sanitizer.AllowedAtRules.Clear();
sanitizer.AllowDataAttributes = false;
}
/// <summary>
/// Остаются только текстовые теги
/// </summary>
/// <param name="sanitizer"><see cref="HtmlSanitizer"/></param>
private static void PrepareForTextFormatOnly (ref HtmlSanitizer sanitizer)
{
string[] allowedTags =
{
"strong", "b", "em", "i", "u", "hr", "strike", "div", "ol", "ul", "li", "p", "span", "h1", "h2", "h3", "h4"
};
string[] allowedAttributes =
{
"align", "bgcolor", "border", "cellpadding", "cellspacing", "charset", "checked", "class", "clear", "color", "cols", "colspan",
"datetime", "disabled", "headers", "height", "high", "hspace", "label", "lang", "list", "low", "max", "maxlength", "min", "name",
"nowrap", "placeholder", "required", "rev", "rows", "rowspan", "rules", "selected", "size", "span", "spellcheck", "style", "summary",
"tabindex", "title", "type", "valign", "value", "vspace", "width", "wrap"
};
sanitizer.AllowedTags.Clear();
sanitizer.AllowedTags.UnionWith(allowedTags);
sanitizer.AllowedAtRules.Clear();
sanitizer.AllowDataAttributes = false;
sanitizer.AllowedAttributes.Clear();
sanitizer.AllowedAttributes.UnionWith(allowedAttributes);
}
/// <summary>
/// Остаются текстовые теги + изображения и ссылки
/// </summary>
/// <param name="sanitizer"><see cref="HtmlSanitizer"/></param>
private static void PrepareForImageAndLinks (ref HtmlSanitizer sanitizer)
{
PrepareForTextFormatOnly(ref sanitizer);
string[] allowedTags =
{
"a", "img"
};
string[] allowedAttributes =
{
"alt", "href", "hreflang", "nohref", "rel", "src", "target"
};
sanitizer.AllowedTags.UnionWith(allowedTags);
sanitizer.AllowedAttributes.UnionWith(allowedAttributes);
}
/// <summary>
/// Остаются все теги, за исключением IFRAME
/// </summary>
/// <param name="sanitizer"><see cref="HtmlSanitizer"/></param>
private static void PrepareForAllExceptIFrame (ref HtmlSanitizer sanitizer)
{
sanitizer.AllowedTags.Remove("iframe");
}
}

View File

@@ -0,0 +1,38 @@
namespace anbs_cp.ForNet.Enums;
/// <summary>
/// Уровень очистки текста
/// атрибуты описаны на стр. https://github.com/mganss/HtmlSanitizer/wiki/Options
/// </summary>
public enum ESanitizerLevel
{
/// <summary>
/// Все html-теги под запретом
/// </summary>
NoTags = 0,
/// <summary>
/// Доступны только:
/// * теги формата шрифта (жирный, курсив, подчёркнутый, зачёркнутый)
/// * теги расположения текста (слева, по центру, справа)
/// </summary>
TextFormatOnly = 1,
/// <summary>
/// Доступны только:
/// * все теги уровня lvlTextFormatOnly
/// * теги ссылки
/// * теги изображения
/// </summary>
ImageAndLinks = 2,
/// <summary>
/// Доступны все теги, кроме вставки с другого сайта
/// </summary>
AllExceptIFrame = 3,
/// <summary>
/// Доступны все теги
/// </summary>
All = 4
}

View File

@@ -6,7 +6,7 @@
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageId>ANBSoftware.ComponentsPackForNet</PackageId>
<Version>2023.11.15.0</Version>
<Version>2023.11.25.0</Version>
<Authors>Александр Бабаев</Authors>
<Product>Набор компонентов ANB Software для ASP.NET Core</Product>
<Description>Библиотека полезных методов языка C# для ASP.NET Core</Description>
@@ -20,6 +20,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HtmlSanitizer" Version="8.0.795" />
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />