-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule.go
367 lines (296 loc) · 9.95 KB
/
rule.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
package validate
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
// Rule represents a check to run on a request.
type Rule struct {
// Param is the field in the request to check.
Param string
// Check is a callback that is ran against the request.
Check CheckFunc
// Options is a map that is passed to the check func.
Options Options
}
// Options is a map of strings to values that can be used inside
// a CheckFunc to dynamically determine if a criteria has passed.
// Think max length, greater than, between, etc.
type Options map[string]interface{}
// CheckFunc is a function that uses the request, parameter and
// any passed options to determine if a Rule is passed.
type CheckFunc func(*http.Request, string, Options) error
// Required returns an error if the parameter is not in the request.
// Additional checks should be made to ensure it is not empty, etc.
var Required CheckFunc = func(r *http.Request, param string, _ Options) error {
if _, exists := r.Form[param]; !exists {
return fmt.Errorf("%s is required", param)
}
return nil
}
// Empty returns an error if the parameter is empty. That is, it
// exists in the request, but is an empty string.
var Empty CheckFunc = func(r *http.Request, param string, _ Options) error {
value := r.Form.Get(param)
if value == "" {
return fmt.Errorf("%s cannot be empty", param)
}
return nil
}
// Alpha returns an error if the parameter contains any characters
// that are not in the alphabet, represented by the regular
// expression `[a-zA-Z]+`.
var Alpha CheckFunc = func(r *http.Request, param string, _ Options) error {
fail, _ := regexp.MatchString(`[^a-zA-Z]+`, r.Form.Get(param))
if fail {
return fmt.Errorf("%s must only contain alphabetical characters", param)
}
return nil
}
// Alphanumeric returns an error if the parameter contains
// any characters that are not letters or numbers.
var Alphanumeric CheckFunc = func(r *http.Request, param string, _ Options) error {
fail, _ := regexp.MatchString(`[^a-zA-Z0-9]+`, r.Form.Get(param))
if fail {
return fmt.Errorf("%s must only contain alphanumeric characters", param)
}
return nil
}
// Integer returns an error if the parameter cannot be converted
// to an integer.
var Integer CheckFunc = func(r *http.Request, param string, _ Options) error {
_, err := strconv.Atoi(r.Form.Get(param))
if err != nil {
return fmt.Errorf("%s must be an integer", param)
}
return nil
}
// Boolean returns an error if the parameter contains a value
// that is not boolean. Because these values are coming in
// via a HTTP request (and are therefore strings), a boolean
// value must be inferred.
var Boolean CheckFunc = func(r *http.Request, param string, _ Options) error {
value := r.Form.Get(param)
if value == "true" || value == "false" || value == "1" || value == "0" {
return nil
}
return fmt.Errorf("%s must be a boolean value", param)
}
// MaxLength returns an error if the parameter length (number
// of characters) exceeds the length set in the Options map
// passed to the Rule.
var MaxLength CheckFunc = func(r *http.Request, param string, o Options) error {
value := r.Form.Get(param)
max, ok := o["length"].(int)
if !ok {
max = 0
}
if len(value) > max {
return fmt.Errorf("%s cannot be longer than %d characters", param, max)
}
return nil
}
// MinLength returns an error if the parameter length (number
// of characters) is shorter than the length set in the Options
// map passed to the Rule.
var MinLength CheckFunc = func(r *http.Request, param string, o Options) error {
value := r.Form.Get(param)
min, ok := o["length"].(int)
if !ok {
min = 0
}
if len(value) < min {
return fmt.Errorf("%s must be longer than %d characters", param, min)
}
return nil
}
// Regex returns an error if the parameter does not satisfy
// the regular expression passed in the Options map.
var Regex CheckFunc = func(r *http.Request, param string, o Options) error {
value := r.Form.Get(param)
pattern, ok := o["pattern"].(string)
if !ok {
return fmt.Errorf("unable to create regex to validate %s parameter", param)
}
if pass, _ := regexp.MatchString(pattern, value); !pass {
return fmt.Errorf("%s did not match regex `%s`", param, pattern)
}
return nil
}
// NotRegex returns an error if the parameter value is satisfied
// by the regular expression passed in the Options map.
var NotRegex CheckFunc = func(r *http.Request, param string, o Options) error {
value := r.Form.Get(param)
pattern, ok := o["pattern"].(string)
if !ok {
return fmt.Errorf("unable to create regex to validate %s parameter", param)
}
if pass, _ := regexp.MatchString(pattern, value); pass {
return fmt.Errorf("%s must not match regex `%s`", param, pattern)
}
return nil
}
// MXEmail looks up the MX Records on a domain to check if a record exists. If
// an MX record exists, it is likely that the email address is real. This is
// smarter than just checking if an email address fits a certain format.
var MXEmail CheckFunc = func(r *http.Request, param string, o Options) error {
if err := Email(r, param, nil); err != nil {
return err
}
timeout, ok := o["timeout"].(int)
if !ok {
timeout = 5
}
domain := getDomain(r.Form.Get(param))
records, err := getMXRecords(r.Context(), domain, timeout)
if err != nil {
return fmt.Errorf("the host %s is not a valid email provider", domain)
}
if len(records) == 0 {
return fmt.Errorf("no MX records exist for %s", param)
}
return nil
}
// TelnetEmail uses a telnet connection to dial into the mail provider
// for the given email address and uses this connection to verify if
// an email address is valid.
//
// TODO: Mixed results on Outlook/Hotmail.
var TelnetEmail CheckFunc = func(r *http.Request, param string, _ Options) error {
if err := Email(r, param, nil); err != nil {
return err
}
address := r.Form.Get(param)
domain := getDomain(address)
records, err := getMXRecords(r.Context(), domain, 5)
if err != nil || len(records) == 0 {
return fmt.Errorf("no MX records exist for %s", param)
}
conn, err := net.Dial("tcp", records[0].Host+":25")
if err != nil {
return fmt.Errorf("unable to connect to %s to validate email", domain)
}
defer conn.Close()
responder := bufio.NewReader(conn)
// Discards the first line of the telnet connection
// so we are ready to send some commands to it.
responder.ReadString('\n')
commands := []string{
"helo hi",
"mail from: <[email protected]>",
fmt.Sprintf("rcpt to: <%s>", address),
}
var msg string
for _, cmd := range commands {
fmt.Fprintf(conn, cmd+"\n")
msg, _ = responder.ReadString('\n')
}
if msg[0:3] != "250" {
return fmt.Errorf("%s is not a valid email address", address)
}
return nil
}
// Email returns an error if the parameter value is not a valid
// email address.
var Email CheckFunc = func(r *http.Request, param string, _ Options) error {
value := r.Form.Get(param)
atCount := strings.Count(value, "@")
// If there is not one @ sign in the string, it is not
// a valid email address.
if atCount != 1 {
return fmt.Errorf("%s is not a valid email address", param)
}
if pass, _ := regexp.MatchString(`^[^@\s]+@[^@\s]+$`, value); pass {
return nil
}
return fmt.Errorf("%s is not a valid email address", param)
}
// RFC3339 returns an error if the parameter does not satisfy
// the RFC3339 format.
var RFC3339 CheckFunc = func(r *http.Request, param string, _ Options) error {
return DateFormat(r, param, Options{"format": time.RFC3339})
}
// RFC1123 returns an error if the parameter does not satisfy
// the RFC1123 format.
var RFC1123 CheckFunc = func(r *http.Request, param string, _ Options) error {
return DateFormat(r, param, Options{"format": time.RFC1123})
}
// RFC822 returns an error if the parameter does not satisfy the
// RFC822 format.
var RFC822 CheckFunc = func(r *http.Request, param string, _ Options) error {
return DateFormat(r, param, Options{"format": time.RFC822})
}
// UnixDate returns an error if the parameter does not satisfy
// the format defined in Go's UnixDate const.
var UnixDate CheckFunc = func(r *http.Request, param string, _ Options) error {
return DateFormat(r, param, Options{"format": time.UnixDate})
}
// DateFormat returns an error if the parameter does not
// satisfy the date format passed in the Options struct.
var DateFormat CheckFunc = func(r *http.Request, param string, o Options) error {
value := r.Form.Get(param)
format, ok := o["format"].(string)
if !ok {
return fmt.Errorf("unable to create date format string")
}
if _, err := time.Parse(format, value); err != nil {
return fmt.Errorf("%s does not satisfy date format %s", param, format)
}
return nil
}
// Date is a comprehensive validator that returns an error if
// the parameter does not satisfy any of Go's built-in date
// formats.
//
// To validate against additional custom formats, you can pass
// a slice of strings to the Options struct using a `formats` key.
var Date CheckFunc = func(r *http.Request, param string, o Options) error {
formats := []string{
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC3339Nano,
// TODO: These are times... Maybe move them?
time.Kitchen,
time.Stamp,
time.StampMilli,
time.StampMicro,
time.StampNano,
}
customFormats, exists := o["formats"]
if exists {
customFormats, ok := customFormats.([]string)
if !ok {
return fmt.Errorf("unable to create date format string")
}
formats = append(formats, customFormats...)
}
for _, format := range formats {
if err := DateFormat(r, param, Options{"format": format}); err == nil {
return nil
}
}
return fmt.Errorf("%s does not satisfy and date format", param)
}
func getMXRecords(ctx context.Context, domain string, timeout int) ([]*net.MX, error) {
rsv := net.Resolver{}
ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
defer cancel()
return rsv.LookupMX(ctx, domain)
}
func getDomain(email string) string {
parts := strings.Split(email, "@")
return parts[len(parts)-1]
}