2023-03-12 18:00:57 +03:00
|
|
|
// GoToSocial
|
|
|
|
// Copyright (C) GoToSocial Authors admin@gotosocial.org
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2021-08-29 17:52:23 +03:00
|
|
|
|
2021-09-01 19:29:25 +03:00
|
|
|
package validate
|
2021-08-29 17:52:23 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
"github.com/go-playground/validator/v10"
|
2021-09-01 19:29:25 +03:00
|
|
|
"github.com/superseriousbusiness/gotosocial/internal/regexes"
|
2021-08-29 17:52:23 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var v *validator.Validate
|
|
|
|
|
2021-08-30 21:20:27 +03:00
|
|
|
func ulidValidator(fl validator.FieldLevel) bool {
|
|
|
|
field := fl.Field()
|
2021-08-29 17:52:23 +03:00
|
|
|
|
2021-08-30 21:20:27 +03:00
|
|
|
switch field.Kind() {
|
|
|
|
case reflect.String:
|
2021-09-01 19:29:25 +03:00
|
|
|
return regexes.ULID.MatchString(field.String())
|
2021-08-30 21:20:27 +03:00
|
|
|
default:
|
2021-08-29 17:52:23 +03:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
v = validator.New()
|
2021-09-02 13:24:18 +03:00
|
|
|
if err := v.RegisterValidation("ulid", ulidValidator); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-08-29 17:52:23 +03:00
|
|
|
}
|
|
|
|
|
2021-09-01 19:29:25 +03:00
|
|
|
// Struct validates the passed struct, returning validator.ValidationErrors if invalid, or nil if OK.
|
|
|
|
func Struct(s interface{}) error {
|
2021-09-03 12:12:19 +03:00
|
|
|
return processValidationError(v.Struct(s))
|
2021-08-29 17:52:23 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func processValidationError(err error) error {
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if ive, ok := err.(*validator.InvalidValidationError); ok {
|
|
|
|
panic(ive)
|
|
|
|
}
|
|
|
|
|
2022-04-02 16:40:09 +03:00
|
|
|
valErr, ok := err.(validator.ValidationErrors)
|
|
|
|
if !ok {
|
|
|
|
panic("*validator.InvalidValidationError could not be coerced to validator.ValidationErrors")
|
|
|
|
}
|
|
|
|
|
|
|
|
return valErr
|
2021-08-29 17:52:23 +03:00
|
|
|
}
|