-
Notifications
You must be signed in to change notification settings - Fork 14
/
validator.go
199 lines (162 loc) · 4.75 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
package binding
import (
"fmt"
"regexp"
"sync"
"time"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
vEn "github.com/go-playground/validator/v10/translations/en"
"github.com/pariz/gountries"
"github.com/coretrix/hitrix/pkg/errors"
"github.com/coretrix/hitrix/service"
)
var (
once sync.Once
singleton *Validator
)
type Validator struct {
validator *validator.Validate
translator ut.Translator
}
func (t *Validator) ValidateStruct(s interface{}) error {
err := t.validator.Struct(s)
if err != nil {
var fieldErrors errors.FieldErrors = make(map[string]string)
validatorErrs := err.(validator.ValidationErrors)
for _, e := range validatorErrs {
translatedErr := e.Translate(t.translator)
fieldErrors[e.Field()] = translatedErr
}
return fieldErrors
}
return nil
}
func (t *Validator) Engine() interface{} {
return t.validator
}
func (t *Validator) Validate(field interface{}, rules string) []error {
err := t.validator.Var(field, rules)
return t.translateError(err)
}
func NewValidator() *Validator {
once.Do(func() {
validatorInstance := validator.New()
validatorInstance.SetTagName("binding")
english := en.New()
uni := ut.New(english, english)
translator, _ := uni.GetTranslator("en")
for _, customValidation := range customValidations {
err := validatorInstance.RegisterValidation(customValidation.RuleName, customValidation.ValidatorFunction)
if err != nil {
panic(err)
}
err = validatorInstance.RegisterTranslation(
customValidation.RuleName,
translator, customValidation.CustomRegisFunc,
customValidation.CustomTransFunc,
)
if err != nil {
panic(err)
}
}
_ = vEn.RegisterDefaultTranslations(validatorInstance, translator)
singleton = &Validator{validator: validatorInstance, translator: translator}
})
return singleton
}
func (t *Validator) translateError(err error) (errs []error) {
if err == nil {
return nil
}
validatorErrs := err.(validator.ValidationErrors)
for _, e := range validatorErrs {
translatedErr := fmt.Errorf(e.Translate(t.translator))
errs = append(errs, translatedErr)
}
return errs
}
type CustomValidation struct {
RuleName string
ValidatorFunction func(validator.FieldLevel) bool
CustomRegisFunc validator.RegisterTranslationsFunc
CustomTransFunc validator.TranslationFunc
}
var customValidations = []CustomValidation{
{
RuleName: "timestamp_gte_today",
ValidatorFunction: validateTimestampGteToday,
CustomRegisFunc: func(ut ut.Translator) error {
return ut.Add("timestamp_gte_today", "value should be greater than today", true)
},
CustomTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T("timestamp_gte_today", fe.Field())
return t
},
},
{
RuleName: "country_code_custom",
ValidatorFunction: validateCountryCodeAlpha2,
CustomRegisFunc: func(ut ut.Translator) error {
return ut.Add("country_code_custom", "not a valid Country Code", true)
},
CustomTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T("country_code_custom", fe.Field())
return t
},
},
{
RuleName: "password_strength",
ValidatorFunction: validatePasswordStrength(8),
CustomRegisFunc: func(ut ut.Translator) error {
return ut.Add(
"password_strength",
"Not strong enough. Should be more than 8 character, contain at least 1 lowercase, 1 uppercase, 1 number, and 1 special character.",
false)
},
CustomTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T("password_strength", fe.Field())
return t
},
},
}
func validateCountryCodeAlpha2(fl validator.FieldLevel) bool {
query := gountries.New()
_, err := query.FindCountryByAlpha(fl.Field().String())
return err == nil
}
func validateTimestampGteToday(fl validator.FieldLevel) bool {
value := time.UnixMilli(fl.Field().Int())
var today time.Time
if service.HasService(service.ClockService) {
today = service.DI().Clock().Now().Truncate(time.Hour)
} else {
today = time.Now().Truncate(time.Hour)
}
return today.Before(value)
}
func validatePasswordStrength(minLength int) func(fl validator.FieldLevel) bool {
return func(fl validator.FieldLevel) bool {
pass := fl.Field().String()
if len(pass) < minLength {
return false
}
ok, _ := regexp.MatchString(`[a-z]+`, pass)
if !ok {
return false
}
ok, _ = regexp.MatchString(`[A-Z]+`, pass)
if !ok {
return false
}
ok, _ = regexp.MatchString(`[0-9]+`, pass)
if !ok {
return false
}
// ref: https://owasp.org/www-community/password-special-characters
specialChars := " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
ok, _ = regexp.MatchString("["+specialChars+"]+", pass)
return ok
}
}