Skip to content

Commit 3c6bc48

Browse files
committed
Prevent SQL injection when passing sort
1 parent 5d0ccb7 commit 3c6bc48

1 file changed

Lines changed: 15 additions & 5 deletions

File tree

page.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,20 @@ func (s Sort) String() string {
3737
return fmt.Sprintf("%s %s", s.Column, s.Order)
3838
}
3939

40-
var _MatcherOrderBy = regexp.MustCompile(`-?([a-zA-Z0-9]+)`)
40+
func (s Sort) IsValid() bool {
41+
return s.Column != "" && _MatcherOrderBy.MatchString(s.Column)
42+
}
43+
44+
var _MatcherOrderBy = regexp.MustCompile(`^-?([a-zA-Z_][a-zA-Z0-9_]*)$`)
4145

4246
func NewSort(s string) (Sort, bool) {
43-
if s == "" || !_MatcherOrderBy.MatchString(s) {
44-
return Sort{}, false
45-
}
4647
sort := Sort{
4748
Column: s,
4849
Order: Asc,
4950
}
51+
if !sort.IsValid() {
52+
return Sort{}, false
53+
}
5054
if strings.HasPrefix(s, "-") {
5155
sort.Column = s[1:]
5256
sort.Order = Desc
@@ -79,7 +83,13 @@ func NewPage(size, page uint32, sort ...Sort) *Page {
7983
func (p *Page) GetOrder(defaultSort ...string) []Sort {
8084
// if page has sort, use it
8185
if p != nil && len(p.Sort) != 0 {
82-
return p.Sort
86+
sort := make([]Sort, 0, len(p.Sort))
87+
for _, s := range p.Sort {
88+
if s.IsValid() {
89+
sort = append(sort, s)
90+
}
91+
}
92+
return sort
8393
}
8494
// if page has column, use default sort
8595
if p == nil || p.Column == "" {

0 commit comments

Comments
 (0)