2018-01-30 02:24:42 +02:00
|
|
|
package defaults
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/volatiletech/authboss"
|
|
|
|
)
|
|
|
|
|
|
|
|
// HTTPFormValidator validates HTTP post type inputs
|
|
|
|
type HTTPFormValidator struct {
|
2018-02-05 04:30:39 +02:00
|
|
|
Values map[string]string
|
|
|
|
|
|
|
|
Ruleset []Rules
|
2018-01-30 02:24:42 +02:00
|
|
|
ConfirmFields []string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate validates a request using the given ruleset.
|
2018-02-05 04:30:39 +02:00
|
|
|
func (h HTTPFormValidator) Validate() []error {
|
2018-01-30 02:24:42 +02:00
|
|
|
var errList authboss.ErrorList
|
|
|
|
|
2018-02-05 04:30:39 +02:00
|
|
|
for _, rule := range h.Ruleset {
|
|
|
|
field := rule.FieldName
|
2018-01-30 02:24:42 +02:00
|
|
|
|
2018-02-05 04:30:39 +02:00
|
|
|
val := h.Values[field]
|
|
|
|
if errs := rule.Errors(val); len(errs) > 0 {
|
2018-01-30 02:24:42 +02:00
|
|
|
errList = append(errList, errs...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-05 04:30:39 +02:00
|
|
|
if l := len(h.ConfirmFields); l != 0 && l%2 != 0 {
|
|
|
|
panic("HTTPFormValidator given an odd number of confirm fields")
|
|
|
|
}
|
|
|
|
|
2018-01-30 02:24:42 +02:00
|
|
|
for i := 0; i < len(h.ConfirmFields)-1; i += 2 {
|
2018-02-05 04:30:39 +02:00
|
|
|
main := h.Values[h.ConfirmFields[i]]
|
2018-01-30 02:24:42 +02:00
|
|
|
if len(main) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-02-05 04:30:39 +02:00
|
|
|
confirm := h.Values[h.ConfirmFields[i+1]]
|
2018-01-30 02:24:42 +02:00
|
|
|
if len(confirm) == 0 || main != confirm {
|
|
|
|
errList = append(errList, FieldError{h.ConfirmFields[i+1], fmt.Errorf("Does not match %s", h.ConfirmFields[i])})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return errList
|
|
|
|
}
|
|
|
|
|
|
|
|
// FieldError represents an error that occurs during validation and is always
|
|
|
|
// attached to field on a form.
|
|
|
|
type FieldError struct {
|
|
|
|
FieldName string
|
|
|
|
FieldErr error
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewFieldError literally only exists because of poor name planning
|
|
|
|
// where name and err can't be exported on the struct due to the method names
|
|
|
|
func NewFieldError(name string, err error) FieldError {
|
|
|
|
return FieldError{FieldName: name, FieldErr: err}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name of the field the error is about
|
|
|
|
func (f FieldError) Name() string {
|
|
|
|
return f.FieldName
|
|
|
|
}
|
|
|
|
|
|
|
|
// Err for the field
|
|
|
|
func (f FieldError) Err() error {
|
|
|
|
return f.FieldErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error in string form
|
|
|
|
func (f FieldError) Error() string {
|
|
|
|
return fmt.Sprintf("%s: %v", f.FieldName, f.FieldErr)
|
|
|
|
}
|