Adding sorting lists.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 58s
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 58s
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package data
|
||||
|
||||
import "greenlight.craftr.fr/internal/validator"
|
||||
import (
|
||||
"greenlight.craftr.fr/internal/validator"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Filters struct {
|
||||
Page int
|
||||
@@ -19,3 +22,23 @@ func ValidateFilters(v *validator.Validator, f Filters) {
|
||||
// Check that the sort parameter matches a value in the safelist
|
||||
v.Check(validator.PermittedValue(f.Sort, f.SortSafelist...), "sort", "invalid sort value")
|
||||
}
|
||||
|
||||
// sortColumn : Check that the client-provided Sort field matches one of the entries in our safelist and if it does, extract the column name from the Sort field by stripping the leading hyphen character (if one exists)
|
||||
func (f Filters) sortColumn() string {
|
||||
for _, safeValue := range f.SortSafelist {
|
||||
if f.Sort == safeValue {
|
||||
return strings.TrimPrefix(f.Sort, "-")
|
||||
}
|
||||
}
|
||||
|
||||
// It will panic if the client-provided 'Sort' value doesn't match one of the entries in our safelist. In theory, this shouldn't happen - the 'Sort' value should have already been checked by calling the 'ValidateFilters()' function - but this is a sensible failsafe to help stop a SQL injection attack occurring
|
||||
panic("unsafe sort parameter: " + f.Sort)
|
||||
}
|
||||
|
||||
// sortDirection : Return the sort direction ("ASC" or "DESC") depending on the prefix character of the Sort field
|
||||
func (f Filters) sortDirection() string {
|
||||
if strings.HasPrefix(f.Sort, "-") {
|
||||
return "DESC"
|
||||
}
|
||||
return "ASC"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user