Sanitize at API level

This commit is contained in:
breel
2020-07-25 19:40:31 -06:00
parent a1d59a0248
commit 09507d38e9
4 changed files with 88 additions and 20 deletions

View File

@@ -2,7 +2,6 @@ package operator
import (
"fmt"
"regexp"
"strings"
"go.mongodb.org/mongo-driver/bson"
@@ -26,14 +25,10 @@ func (cis CaseInsensitives) MarshalBSON() ([]byte, error) {
values := cis.Values
if len(cis.Values) == 0 {
values = []string{".*"}
} else {
for i := range values {
values[i] = escapeRegex(values[i])
}
}
ci := CaseInsensitive{
Key: cis.Key,
Value: fmt.Sprintf("^(%s)$", strings.Join(values, "|")),
Value: fmt.Sprintf("(%s)", strings.Join(values, "|")),
}
return bson.Marshal(ci)
}
@@ -46,11 +41,9 @@ type CaseInsensitive struct {
func (ci CaseInsensitive) MarshalBSON() ([]byte, error) {
value := ci.Value
if value == "" {
value = "^$"
} else {
value = escapeRegex(value)
value = ".*"
}
return bson.Marshal(Regex{Key: ci.Key, Value: "(?i)" + ci.Value})
return bson.Marshal(Regex{Key: ci.Key, Value: "^(?i)" + value + "$"})
}
type FilterIn struct {
@@ -107,9 +100,3 @@ func filterMarshal(op, key string, value interface{}) ([]byte, error) {
}
return bson.Marshal(m)
}
func escapeRegex(s string) string {
re := regexp.MustCompile(`[^a-zA-Z0-9]`)
s = re.ReplaceAllString(s, `.`)
return s
}