Unverified Commit b760882e authored by Alex Saskevich's avatar Alex Saskevich Committed by GitHub

Revert "(Enhancement) Validator: Adding more concrete base64 validation,...

Revert "(Enhancement) Validator: Adding more concrete base64 validation, Enabling []int validation "
parent 44967462
......@@ -307,8 +307,6 @@ Here is a list of available validators for struct fields (validator - used funct
"halfwidth": IsHalfWidth,
"variablewidth": IsVariableWidth,
"base64": IsBase64,
"base64string": IsBase64String,
"base64rawstring": IsBase64RawString,
"datauri": IsDataURI,
"ip": IsIP,
"port": IsPort,
......@@ -334,7 +332,6 @@ Validators with parameters
"runelength(min|max)": RuneLength,
"matches(pattern)": StringMatches,
"in(string1|string2|...|stringN)": IsIn,
"inintarr(string1|string2|...|stringN)": InIntArr,
```
And here is small example of usage:
......
......@@ -14,10 +14,6 @@ type Validator func(str string) bool
// The second parameter should be the context (in the case of validating a struct: the whole object being validated).
type CustomTypeValidator func(i interface{}, o interface{}) bool
// ArrayValidator is a wrapper for validator functions that returns bool and accepts any type.
// The second parameter functions like the ParamValidator function where one can provide values to check against the array.
type ArrayValidator func(i interface{}, params ...string) bool
// ParamValidator is a wrapper for validator functions that accepts additional parameters.
type ParamValidator func(str string, params ...string) bool
type tagOptionsMap map[string]tagOption
......@@ -72,16 +68,6 @@ var ParamTagRegexMap = map[string]*regexp.Regexp{
"rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"),
}
// ArrayTagMap is a map of functions accept variants parameters
var ArrayTagMap = map[string]ArrayValidator{
"inintarr": isInIntRaw,
}
// ArrayTagRegexMap maps param tags to their respective regexes.
var ArrayTagRegexMap = map[string]*regexp.Regexp{
"inintarr": regexp.MustCompile(`^inintarr\((.*)\)`),
}
type customTypeTagMap struct {
validators map[string]CustomTypeValidator
......@@ -143,8 +129,6 @@ var TagMap = map[string]Validator{
"halfwidth": IsHalfWidth,
"variablewidth": IsVariableWidth,
"base64": IsBase64,
"base64string": IsBase64String,
"base64rawstring": IsBase64RawString,
"datauri": IsDataURI,
"ip": IsIP,
"port": IsPort,
......
......@@ -484,37 +484,11 @@ func IsVariableWidth(str string) bool {
return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str)
}
// IsBase64 check if a string is data:base64 encoded.
// IsBase64 check if a string is base64 encoded.
func IsBase64(str string) bool {
return rxBase64.MatchString(str)
}
// IsBase64String check to see if the string raw inputted string is a valid base64
func IsBase64String(str string) bool {
if len(str) == 0 {
return false
}
_, err := base64.URLEncoding.DecodeString(str)
if err != nil {
return false
}
return true
}
// IsBase64RawString check to see if the string raw inputted (no == at the end) string is a valid base64
func IsBase64RawString(str string) bool {
if len(str) == 0 {
return false
}
_, err := base64.RawURLEncoding.DecodeString(str)
if err != nil {
return false
}
return true
}
// IsFilePath check is a string is Win or Unix file path and returns it's type.
func IsFilePath(str string) (bool, int) {
if rxWinPath.MatchString(str) {
......@@ -1196,42 +1170,6 @@ func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options
}
return result, nil
case reflect.Slice, reflect.Array:
for validatorSpec, customErrorMessage := range options {
var negate bool
validator := validatorSpec
customMsgExists := len(customErrorMessage) > 0
// Check whether the tag looks like '!something' or 'something'
if validator[0] == '!' {
validator = validator[1:]
negate = true
}
for key, value := range ArrayTagRegexMap {
ps := value.FindStringSubmatch(validator)
if len(ps) == 0 {
continue
}
validatefunc, ok := ArrayTagMap[key]
if !ok {
continue
}
delete(options, validatorSpec)
if result := validatefunc(v.Interface(), ps[1:]...); (!result && !negate) || (result && negate) {
if customMsgExists {
return false, Error{t.Name, fmt.Errorf(customErrorMessage), customMsgExists, stripParams(validatorSpec)}
}
if negate {
return false, Error{t.Name, fmt.Errorf("%v does validate as %v", v.Interface(), validator), customMsgExists, stripParams(validatorSpec)}
}
return false, Error{t.Name, fmt.Errorf("%v does not validate as %v", v.Interface(), validator), customMsgExists, stripParams(validatorSpec)}
}
}
}
result := true
for i := 0; i < v.Len(); i++ {
var resultItem bool
......@@ -1329,41 +1267,6 @@ func ErrorsByField(e error) map[string]string {
return m
}
// InIntArr loops over the structs []int and checks if the params passed in
// are inside that array
func InIntArr(i interface{}, params ...string) bool {
switch i.(type) {
case []int:
arr := i.([]int)
for _, a := range arr {
var valid bool
for _, p := range params {
value, err := strconv.Atoi(p)
if err != nil {
return false
}
if value == a {
valid = true
break
}
}
if !valid {
return false
}
}
}
return true
}
func isInIntRaw(i interface{}, params ...string) bool {
if len(params) == 1 {
rawParams := params[0]
parsedParams := strings.Split(rawParams, "|")
return InIntArr(i, parsedParams...)
}
return false
}
// Error returns string equivalent for reflect.Type
func (e *UnsupportedTypeError) Error() string {
return "validator: unsupported type: " + e.Type.String()
......
......@@ -1093,7 +1093,7 @@ func TestIsDivisibleBy(t *testing.T) {
// This small example illustrate how to work with IsDivisibleBy function.
func ExampleIsDivisibleBy() {
fmt.Println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
}
func TestIsByteLength(t *testing.T) {
......@@ -1535,62 +1535,6 @@ func TestIsBase64(t *testing.T) {
}
}
func TestIsBase64String(t *testing.T) {
t.Parallel()
var tests = []struct {
param string
expected bool
}{
{"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true},
{"Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true},
{"U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", true},
{"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
"UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
"rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
"FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
"QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
"Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", false},
{"12345", false},
{"", false},
{"Vml2YW11cyBmZXJtZtesting123", false},
}
for _, test := range tests {
actual := IsBase64String(test.param)
if actual != test.expected {
t.Errorf("Expected IsBase64(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}
func TestIsBase64RawString(t *testing.T) {
t.Parallel()
var tests = []struct {
param string
expected bool
}{
{"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4", true},
{"Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg", true},
{"U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw", true},
{"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
"UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
"rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
"FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
"QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
"Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", false},
{"12345", false},
{"", false},
{"Vml2YW11cyBmZXJtZtesting123", true},
}
for _, test := range tests {
actual := IsBase64RawString(test.param)
if actual != test.expected {
t.Errorf("Expected IsBase64(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}
func TestIsISO3166Alpha2(t *testing.T) {
t.Parallel()
......@@ -3225,9 +3169,9 @@ func ExampleValidateStruct() {
result, err := ValidateStruct(post)
if err != nil {
fmt.Println("error: " + err.Error())
println("error: " + err.Error())
}
fmt.Println(result)
println(result)
}
func TestValidateStructParamValidatorInt(t *testing.T) {
......@@ -3544,39 +3488,3 @@ bQIDAQAB
}
}
}
func TestInIntArr(t *testing.T) {
t.Parallel()
var tests = []struct {
arr []int
expected bool
wantErr bool
}{
{arr: []int{1, 2, 3}, expected: true, wantErr: false},
{arr: []int{6}, expected: true, wantErr: false},
{arr: []int{1, 2, 3, 4, 5, 6}, expected: true, wantErr: false},
{arr: []int{1, 2, 3, 4, 5, 6, 7}, expected: false, wantErr: true},
{arr: []int{0, 2, 3, 4, 5, 6}, expected: false, wantErr: true},
{arr: []int{1, 2, 3, 8, 5, 6}, expected: false, wantErr: true},
{arr: []int{1, 2, 6}, expected: true, wantErr: false},
}
type mockStruct struct {
Arr []int `valid:"inintarr(1|2|3|4|5|6)"`
}
for _, tt := range tests {
m := mockStruct{tt.arr}
ok, err := ValidateStruct(m)
if tt.wantErr && err == nil {
t.Error("Expected err with optional validation, got nil")
}
if tt.expected != ok {
t.Errorf("Expected validation to return %v, got %v", tt.expected, ok)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment