add input sanitizer

This commit is contained in:
aichy126 2023-02-15 15:51:12 +08:00
parent 921cd3465f
commit edc06942d5
3 changed files with 24 additions and 6 deletions

View File

@ -33,6 +33,7 @@ import (
"github.com/go-playground/validator/v10/translations/vi"
"github.com/go-playground/validator/v10/translations/zh"
"github.com/go-playground/validator/v10/translations/zh_tw"
"github.com/microcosm-cc/bluemonday"
myErrors "github.com/segmentfault/pacman/errors"
"github.com/segmentfault/pacman/i18n"
"github.com/segmentfault/pacman/log"
@ -116,10 +117,27 @@ func NotBlank(fl validator.FieldLevel) (res bool) {
}
}
func Sanitizer(fl validator.FieldLevel) (res bool) {
field := fl.Field()
switch field.Kind() {
case reflect.String:
filter := bluemonday.UGCPolicy()
field.SetString(filter.Sanitize(field.String()))
return true
case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array:
return field.Len() > 0
case reflect.Ptr, reflect.Interface, reflect.Func:
return !field.IsNil()
default:
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
}
func createDefaultValidator(la i18n.Language) *validator.Validate {
validate := validator.New()
// _ = validate.RegisterValidation("notblank", validators.NotBlank)
_ = validate.RegisterValidation("notblank", NotBlank)
_ = validate.RegisterValidation("sanitizer", Sanitizer)
validate.RegisterTagNameFunc(func(fld reflect.StructField) (res string) {
defer func() {
if len(res) > 0 {

View File

@ -205,7 +205,7 @@ func (sc *SiteInfoController) UpdateGeneral(ctx *gin.Context) {
return
}
err := sc.siteInfoService.SaveSiteGeneral(ctx, req)
handler.HandleResponse(ctx, err, nil)
handler.HandleResponse(ctx, err, req)
}
// UpdateInterface update site interface

View File

@ -18,11 +18,11 @@ const PermaLinkQuestionID = 2
// SiteGeneralReq site general request
type SiteGeneralReq struct {
Name string `validate:"required,gt=1,lte=128" form:"name" json:"name"`
ShortDescription string `validate:"omitempty,gt=3,lte=255" form:"short_description" json:"short_description"`
Description string `validate:"omitempty,gt=3,lte=2000" form:"description" json:"description"`
SiteUrl string `validate:"required,gt=1,lte=512,url" form:"site_url" json:"site_url"`
ContactEmail string `validate:"required,gt=1,lte=512,email" form:"contact_email" json:"contact_email"`
Name string `validate:"required,sanitizer,gt=1,lte=128" form:"name" json:"name"`
ShortDescription string `validate:"omitempty,sanitizer,gt=3,lte=255" form:"short_description" json:"short_description"`
Description string `validate:"omitempty,sanitizer,gt=3,lte=2000" form:"description" json:"description"`
SiteUrl string `validate:"required,sanitizer,gt=1,lte=512,url" form:"site_url" json:"site_url"`
ContactEmail string `validate:"required,sanitizer,gt=1,lte=512,email" form:"contact_email" json:"contact_email"`
}
type SiteSeoReq struct {