1
0

Added validation for structs (#19)

This commit is contained in:
konrad
2018-11-16 23:17:37 +00:00
committed by Gitea
parent 373bbd2202
commit 0c544fe355
299 changed files with 135 additions and 64237 deletions

View File

@ -17,6 +17,11 @@ func (c *WebHandler) CreateWeb(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, "No or invalid model provided.")
}
// Validate the struct
if err := ctx.Validate(currentStruct); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err)
}
// Get the user to pass for later checks
currentUser, err := models.GetCurrentUser(ctx)
if err != nil {

View File

@ -18,6 +18,11 @@ func (c *WebHandler) UpdateWeb(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, "No or invalid model provided.")
}
// Validate the struct
if err := ctx.Validate(currentStruct); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err)
}
// Check if the user has the right to do that
currentUser, err := models.GetCurrentUser(ctx)
if err != nil {

View File

@ -11,17 +11,42 @@
package routes
import (
"code.vikunja.io/api/pkg/models"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/swaggo/echo-swagger"
_ "code.vikunja.io/api/docs" // To generate swagger docs
"code.vikunja.io/api/pkg/models"
apiv1 "code.vikunja.io/api/pkg/routes/api/v1"
"code.vikunja.io/api/pkg/routes/crud"
"github.com/asaskevich/govalidator"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/spf13/viper"
"github.com/swaggo/echo-swagger"
)
// CustomValidator is a dummy struct to use govalidator with echo
type CustomValidator struct{}
// Validate validates stuff
func (cv *CustomValidator) Validate(i interface{}) error {
if _, err := govalidator.ValidateStruct(i); err != nil {
var errs []string
for field, e := range govalidator.ErrorsByField(err) {
errs = append(errs, field+": "+e)
}
httperr := models.ValidationHTTPError{
models.HTTPError{
Code: models.ErrCodeInvalidData,
Message: "Invalid Data",
},
errs,
}
return httperr
}
return nil
}
// NewEcho registers a new Echo instance
func NewEcho() *echo.Echo {
e := echo.New()
@ -33,6 +58,9 @@ func NewEcho() *echo.Echo {
Format: "${time_rfc3339_nano}: ${remote_ip} ${method} ${status} ${uri} ${latency_human} - ${user_agent}\n",
}))
// Validation
e.Validator = &CustomValidator{}
return e
}