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();
}
///
/// Sanitizes a string which should only contain text, but no html.
/// Effectivly removes all html-tags from the string.
///
/// string or null
/// set to true if you plan to use the text as value in html, e.g. contents of a html-tag
/// string or null
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;
}
///
/// Sanitizes html against XSS. Uses default HTMLSanitizer, but allows class-attributes.
///
/// string or null
/// sanitized string or null
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");
}
}
}