Sanitize+truncate display names on registration+change. For #2527
This commit is contained in:
29
utils/strings.go
Normal file
29
utils/strings.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/microcosm-cc/bluemonday"
|
||||
)
|
||||
|
||||
// StripHTML will strip HTML tags from a string.
|
||||
func StripHTML(s string) string {
|
||||
p := bluemonday.NewPolicy()
|
||||
return p.Sanitize(s)
|
||||
}
|
||||
|
||||
// MakeSafeStringOfLength will take a string and strip HTML tags,
|
||||
// trim whitespace, and limit the length.
|
||||
func MakeSafeStringOfLength(s string, length int) string {
|
||||
newString := s
|
||||
newString = StripHTML(newString)
|
||||
|
||||
if len(newString) > length {
|
||||
newString = newString[:length]
|
||||
}
|
||||
|
||||
newString = strings.ReplaceAll(newString, "\r", "")
|
||||
newString = strings.TrimSpace(newString)
|
||||
|
||||
return newString
|
||||
}
|
||||
32
utils/strings_test.go
Normal file
32
utils/strings_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStripHTML tests the StripHTML function.
|
||||
func TestStripHTML(t *testing.T) {
|
||||
requestedString := `<p><img src="img.png"/>Some text</p>`
|
||||
expectedResult := `Some text`
|
||||
|
||||
result := StripHTML(requestedString)
|
||||
fmt.Println(result)
|
||||
|
||||
if result != expectedResult {
|
||||
t.Errorf("Expected %s, got %s", expectedResult, result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSafeString tests the TestSafeString function.
|
||||
func TestSafeString(t *testing.T) {
|
||||
requestedString := `<p><img src="img.png"/> Some text blah blah blah blah blah blahb albh</p>`
|
||||
expectedResult := `Some te`
|
||||
|
||||
result := MakeSafeStringOfLength(requestedString, 10)
|
||||
fmt.Println(result)
|
||||
|
||||
if result != expectedResult {
|
||||
t.Errorf("Expected %s, got %s", expectedResult, result)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user