-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
570 lines (472 loc) · 13.7 KB
/
validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package firevault
import (
"context"
"errors"
"fmt"
"reflect"
"regexp"
"slices"
"strings"
"time"
)
// A ValidationFn is the function that's executed
// during a validation.
type ValidationFn func(ctx context.Context, fs FieldScope) (bool, error)
// holds val func as well as whether it can be called on nil values
type valFnWrapper struct {
fn ValidationFn
runOnNil bool
}
// A TransformationFn is the function that's executed
// during a transformation.
type TransformationFn func(ctx context.Context, fs FieldScope) (interface{}, error)
// holds transform func as well as whether it can be called on nil values
type transFnWrapper struct {
fn TransformationFn
runOnNil bool
}
// An ErrorFormatterFn is the function that's executed
// to generate a custom, user-friendly error message,
// based on FieldError's fields.
//
// If the function returns a nil error, an instance
// of FieldError will be returned instead.
type ErrorFormatterFn func(fe FieldError) error
type validator struct {
validations map[string]valFnWrapper
transformations map[string]transFnWrapper
errFormatters []ErrorFormatterFn
}
func newValidator() *validator {
validator := &validator{
make(map[string]valFnWrapper),
make(map[string]transFnWrapper),
make([]ErrorFormatterFn, 0),
}
// register predefined validators
for name, val := range builtInValidators {
runOnNil := false
// required tags will be called on nil values
if strings.Contains(name, "required") {
runOnNil = true
}
// no need to error check here, built in validations are always valid
_ = validator.registerValidation(name, val, true, runOnNil)
}
// register predefined transformators
for name, trans := range builtInTransformators {
// no need to error check here, built in validations are always valid
_ = validator.registerTransformation(name, trans, true, false)
}
return validator
}
// register a validation
func (v *validator) registerValidation(
name string,
validation ValidationFn,
builtIn bool,
runOnNil bool,
) error {
if v == nil {
return errors.New("firevault: nil validator")
}
if len(name) == 0 {
return errors.New("firevault: validation function name cannot be empty")
}
if !builtIn {
_, found := restrictedTags[name]
if found || strings.ContainsAny(name, restrictedTagChars) {
return errors.New(
"firevault: validation rule contains restricted characters or is the same as a built-in tag",
)
}
}
if validation == nil {
return fmt.Errorf("firevault: validation function %s cannot be empty", name)
}
v.validations[name] = valFnWrapper{validation, runOnNil}
return nil
}
// register a transformation
func (v *validator) registerTransformation(
name string,
transformation TransformationFn,
builtIn bool,
runOnNil bool,
) error {
if v == nil {
return errors.New("firevault: nil validator")
}
if len(name) == 0 {
return errors.New("firevault: transformation function name cannot be empty")
}
if !builtIn {
_, found := restrictedTags[name]
if found || strings.ContainsAny(name, restrictedTagChars) {
return errors.New(
"firevault: transformation rule contains restricted characters or is the same as a built-in tag",
)
}
}
if transformation == nil {
return fmt.Errorf("firevault: transformation function %s cannot be empty", name)
}
v.transformations[name] = transFnWrapper{transformation, runOnNil}
return nil
}
// register an error formatter
func (v *validator) registerErrorFormatter(errFormatter ErrorFormatterFn) error {
if v == nil {
return errors.New("firevault: nil validator")
}
if errFormatter == nil {
return fmt.Errorf("firevault: error formatter function cannot be empty")
}
v.errFormatters = append(v.errFormatters, errFormatter)
return nil
}
// the reflected struct
type reflectedStruct struct {
types reflect.Type
values reflect.Value
}
// check if passed data is a pointer and reflect it if so
func (v *validator) validate(
ctx context.Context,
data interface{},
opts validationOpts,
) (map[string]interface{}, error) {
if v == nil {
return nil, errors.New("firevault: nil validator")
}
rs := reflectedStruct{reflect.TypeOf(data), reflect.ValueOf(data)}
rsValKind := rs.values.Kind()
if rsValKind != reflect.Pointer && rsValKind != reflect.Ptr {
return nil, errors.New("firevault: data must be a pointer to a struct")
}
rs.values = rs.values.Elem()
rs.types = rs.types.Elem()
if rs.values.Kind() != reflect.Struct {
return nil, errors.New("firevault: data must be a pointer to a struct")
}
dataMap, err := v.validateFields(ctx, rs, "", "", opts)
return dataMap, err
}
// loop through struct's fields and validate
// based on provided tags and options
func (v *validator) validateFields(
ctx context.Context,
rs reflectedStruct,
path string,
structPath string,
opts validationOpts,
) (map[string]interface{}, error) {
// map which will hold all fields to pass to firestore
dataMap := make(map[string]interface{})
// iterate over struct fields
for i := 0; i < rs.values.NumField(); i++ {
fieldValue := rs.values.Field(i)
fieldType := rs.types.Field(i)
fs := &fieldScope{
strct: rs.values,
field: fieldType.Name,
structField: fieldType.Name,
displayField: v.getDisplayName(fieldType.Name),
value: fieldValue,
kind: fieldValue.Kind(),
typ: fieldType.Type,
}
tag := fieldType.Tag.Get("firevault")
if tag == "" || tag == "-" {
continue
}
rules := v.parseTag(tag)
// use first tag rule as new field name, if not empty
if rules[0] != "" {
fs.field = rules[0]
}
// get dot-separated field and struct path
fs.path = v.getFieldPath(path, fs.field)
fs.structPath = v.getFieldPath(structPath, fs.structField)
// check if field is of supported type
err := v.validateFieldType(fs.value, fs.path)
if err != nil {
return nil, err
}
// check if field should be skipped based on provided tags
if v.shouldSkipField(fs.value, fs.path, rules, opts) {
continue
}
// check whether to dive into slice/map field
fs.dive = slices.Contains(rules, "dive")
// remove name, dive and omitempty tags from rules, so no validation is attempted
rules = v.cleanRules(rules)
// get pointer value, only if it's not nil
if fs.kind == reflect.Pointer || fs.kind == reflect.Ptr {
if !fs.value.IsNil() {
fs.value = fs.value.Elem()
fs.kind = fs.value.Kind()
fs.typ = fs.value.Type()
}
}
// apply rules (both transformations and validations)
// unless skipped using options
if !opts.skipValidation {
err := v.applyRules(ctx, fs, rules)
if err != nil {
return nil, err
}
// set original struct's field value if changed
if fieldValue != fs.value {
rs.values.Field(i).Set(fs.value)
}
}
// get the final value to be added to the data map
finalValue, err := v.processFinalValue(ctx, fs, opts)
if err != nil {
return nil, err
}
dataMap[fs.field] = finalValue
}
return dataMap, nil
}
// get dot-separated field path
func (v *validator) getFieldPath(path string, fieldName string) string {
if path == "" {
return fieldName
}
return path + "." + fieldName
}
// get field struct name in a human-readable form
func (v *validator) getDisplayName(fieldName string) string {
// handle snake case - replace underscores with spaces
fn := strings.ReplaceAll(fieldName, "_", " ")
// split camel and pascal case
fn = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllStringFunc(fn, func(ns string) string {
return string(ns[0]) + " " + string(ns[1])
})
// check if string contains a number
if regexp.MustCompile(`\d`).MatchString(fn) {
fn = regexp.MustCompile(`([A-Z])([0-9])`).ReplaceAllStringFunc(fn, func(ns string) string {
return string(ns[0]) + " " + string(ns[1])
})
fn = regexp.MustCompile(`([a-z])([0-9])`).ReplaceAllStringFunc(fn, func(ns string) string {
return string(ns[0]) + " " + string(ns[1])
})
}
return fn
}
// check if field is of supported type and return error if not
func (v *validator) validateFieldType(fieldValue reflect.Value, fieldPath string) error {
if !isSupported(fieldValue) {
return errors.New("firevault: unsupported field type - " + fieldPath)
}
return nil
}
// skip field validation if value is zero and an omitempty tag is present
// (unless tags are skipped using options)
func (v *validator) shouldSkipField(
fieldValue reflect.Value,
fieldPath string,
rules []string,
opts validationOpts,
) bool {
omitEmptyMethodTag := string("omitempty_" + opts.method)
shouldOmitEmpty := slices.Contains(rules, "omitempty") || slices.Contains(rules, omitEmptyMethodTag)
if shouldOmitEmpty && !slices.Contains(opts.emptyFieldsAllowed, fieldPath) {
return !hasValue(fieldValue)
}
return false
}
// remove name, dive and omitempty tags from rules
func (v *validator) cleanRules(rules []string) []string {
cleanedRules := make([]string, 0, len(rules))
for index, rule := range rules {
if index != 0 && rule != "omitempty" && rule != string("omitempty_"+create) &&
rule != string("omitempty_"+update) && rule != string("omitempty_"+validate) &&
rule != "dive" {
cleanedRules = append(cleanedRules, rule)
}
}
return cleanedRules
}
// validate field based on rules
func (v *validator) applyRules(
ctx context.Context,
fs *fieldScope,
rules []string,
) error {
for _, rule := range rules {
fe := &fieldError{
field: fs.field,
structField: fs.structField,
displayField: fs.displayField,
path: fs.path,
structPath: fs.structPath,
value: fs.value.Interface(),
kind: fs.kind,
typ: fs.typ,
}
if strings.HasPrefix(rule, "transform=") {
transName := strings.TrimPrefix(rule, "transform=")
fe.tag = transName
fs.tag = transName
if transformation, ok := v.transformations[transName]; ok {
// skip processing if field is zero, unless stated otherwise during rule registration
if !hasValue(fs.value) && !transformation.runOnNil {
continue
}
newValue, err := transformation.fn(ctx, fs)
if err != nil {
return err
}
// check if rule returned a new value and assign it
if newValue != fs.value.Interface() {
fs.value = reflect.ValueOf(newValue)
fs.kind = fs.value.Kind()
fs.typ = fs.value.Type()
}
} else {
return v.formatErr(fe)
}
} else {
// get param value if present
rule, param, _ := strings.Cut(rule, "=")
fe.tag = rule
fs.tag = rule
fe.param = param
fs.param = param
if validation, ok := v.validations[rule]; ok {
// skip processing if field is zero, unless stated otherwise during rule registration
if !hasValue(fs.value) && !validation.runOnNil {
continue
}
ok, err := validation.fn(ctx, fs)
if err != nil {
return err
}
if !ok {
return v.formatErr(fe)
}
} else {
return v.formatErr(fe)
}
}
}
return nil
}
// get final field value based on field's type
func (v *validator) processFinalValue(
ctx context.Context,
fs *fieldScope,
opts validationOpts,
) (interface{}, error) {
switch fs.kind {
case reflect.Struct:
// handle time.Time
if fs.typ == reflect.TypeOf(time.Time{}) {
return fs.value.Interface().(time.Time), nil
}
return v.validateFields(ctx, reflectedStruct{fs.typ, fs.value}, fs.path, fs.structPath, opts)
case reflect.Map:
// return map directly, without validating nested fields
if !fs.dive {
return fs.value.Interface(), nil
}
return v.processMapValue(ctx, fs, opts)
case reflect.Array, reflect.Slice:
// return slice/array directly, without validating nested fields
if !fs.dive {
return fs.value.Interface(), nil
}
return v.processSliceValue(ctx, fs, opts)
default:
return fs.value.Interface(), nil
}
}
// process map's nested fields
func (v *validator) processMapValue(
ctx context.Context,
fs *fieldScope,
opts validationOpts,
) (map[string]interface{}, error) {
newMap := make(map[string]interface{})
iter := fs.value.MapRange()
for iter.Next() {
key := iter.Key()
val := iter.Value()
kind := val.Kind()
if kind == reflect.Pointer {
val = val.Elem()
kind = val.Kind()
}
newFs := &fieldScope{
strct: fs.strct,
field: key.String(),
structField: key.String(),
path: fmt.Sprintf("%s.%v", fs.path, key.Interface()),
structPath: fmt.Sprintf("%s.%v", fs.structPath, key.Interface()),
value: val,
kind: kind,
typ: val.Type(),
}
processedValue, err := v.processFinalValue(ctx, newFs, opts)
if err != nil {
return nil, err
}
newMap[key.String()] = processedValue
}
return newMap, nil
}
// process slice/array's nested fields
func (v *validator) processSliceValue(
ctx context.Context,
fs *fieldScope,
opts validationOpts,
) ([]interface{}, error) {
newSlice := make([]interface{}, fs.value.Len())
for i := 0; i < fs.value.Len(); i++ {
val := fs.value.Index(i)
kind := val.Kind()
if kind == reflect.Pointer {
val = val.Elem()
kind = val.Kind()
}
newFs := &fieldScope{
strct: fs.strct,
field: fmt.Sprintf("[%d]", i),
structField: fmt.Sprintf("[%d]", i),
path: fmt.Sprintf("%s[%d]", fs.path, i),
structPath: fmt.Sprintf("%s[%d]", fs.structPath, i),
value: val,
kind: kind,
typ: val.Type(),
}
processedValue, err := v.processFinalValue(ctx, newFs, opts)
if err != nil {
return nil, err
}
newSlice[i] = processedValue
}
return newSlice, nil
}
// parse rule tags
func (v *validator) parseTag(tag string) []string {
rules := strings.Split(tag, ",")
var validatedRules []string
for _, rule := range rules {
trimmedRule := strings.TrimSpace(rule)
validatedRules = append(validatedRules, trimmedRule)
}
return validatedRules
}
// format fieldError
func (v *validator) formatErr(fe *fieldError) error {
for _, formatter := range v.errFormatters {
err := formatter(fe)
if err != nil {
return err
}
}
return fe
}