-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitizer.go
67 lines (51 loc) · 1.89 KB
/
sanitizer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package htmlsanitizer
import (
"regexp"
"strings"
"github.com/microcosm-cc/bluemonday"
)
var (
p *bluemonday.Policy
policyStripTags *bluemonday.Policy
)
func init() {
p = bluemonday.UGCPolicy()
// "img" is permitted
p.AllowAttrs("align").Matching(bluemonday.ImageAlign).OnElements("img")
p.AllowAttrs("alt").Matching(bluemonday.Paragraph).OnElements("img")
p.AllowAttrs("height", "width").Matching(bluemonday.NumberOrPercent).OnElements("img")
// Standard URLs enabled
p.AllowAttrs("src").OnElements("img")
// Allow in-line images (for now)
p.AllowDataURIImages()
// Style
p.AllowAttrs("style").OnElements("span", "p")
// Allow the 'color' property with valid RGB(A) hex values only (on any element allowed a 'style' attribute)
p.AllowStyles("color").Matching(regexp.MustCompile("(?i)^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$")).Globally()
// Allow the 'text-decoration' property to be set to 'underline', 'line-through' or 'none'
// on 'span' elements only
p.AllowStyles("text-decoration").MatchingEnum("underline", "line-through", "none").OnElements("span", "p")
// Links
// Custom policy based on the origional "AllowStandardURLs" helper func
// URLs must be parseable by net/url.Parse()
p.RequireParseableURLs(true)
// !url.IsAbs() is permitted
p.AllowRelativeURLs(true)
// Most common URL schemes only
p.AllowURLSchemes("mailto", "https")
// For linking elements we will add rel="nofollow" if it does not already exist
// This applies to "a" "area" "link"
p.RequireNoFollowOnLinks(true)
// Custom end
p.AllowAttrs("cite").OnElements("blockquote", "q")
p.AllowAttrs("href").OnElements("a", "area")
p.AllowAttrs("src").OnElements("img")
policyStripTags = bluemonday.StripTagsPolicy()
}
func Sanitize(in string) string {
out := p.Sanitize(in)
return strings.TrimSuffix(out, "<p><br></p>")
}
func StripTags(in string) string {
return policyStripTags.Sanitize(in)
}