66 lines
2.0 KiB
C#
66 lines
2.0 KiB
C#
using Ganss.XSS;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Transactions;
|
|
|
|
|
|
|
|
namespace Blog3000.Shared
|
|
{
|
|
public class InputSanitizer
|
|
{
|
|
|
|
private static InputSanitizer _default = new InputSanitizer();
|
|
|
|
public static InputSanitizer Default { get { return _default; } }
|
|
|
|
private IHtmlSanitizer htmlSanitizer;
|
|
private IHtmlSanitizer htmlRemover;
|
|
|
|
private InputSanitizer()
|
|
{
|
|
Init();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sanitizes a string which should only contain text, but no html.
|
|
/// Effectivly removes all html-tags from the string.
|
|
/// </summary>
|
|
/// <param name="text">string or null</param>
|
|
/// <param name="doHtmlEncoding">set to true if you plan to use the text as value in html, e.g. contents of a html-tag</param>
|
|
/// <returns>string or null</returns>
|
|
public string SanitizeText(string text, bool doHtmlEncoding=false)
|
|
{
|
|
if (text == null) return null;
|
|
|
|
var res = htmlRemover.Sanitize(text);
|
|
if (doHtmlEncoding) res = System.Text.Encodings.Web.HtmlEncoder.Default.Encode(res);
|
|
return res;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sanitizes html against XSS. Uses default HTMLSanitizer, but allows class-attributes.
|
|
/// </summary>
|
|
/// <param name="html">string or null</param>
|
|
/// <returns>sanitized string or null</returns>
|
|
public string SanitizeHtml(string html)
|
|
{
|
|
if (html == null) return null;
|
|
|
|
var res = htmlSanitizer.Sanitize(html);
|
|
return res;
|
|
}
|
|
|
|
|
|
private void Init() {
|
|
htmlRemover = new HtmlSanitizer();
|
|
htmlRemover.AllowedTags.Clear();
|
|
htmlRemover.AllowedSchemes.Clear();
|
|
|
|
htmlSanitizer = new HtmlSanitizer();
|
|
htmlSanitizer.AllowedAttributes.Add("class");
|
|
}
|
|
}
|
|
}
|