From 72a9debaff3a4abd164416633116e7cccfe3eca8 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 14 Aug 2026 10:15:33 +0800 Subject: [PATCH] refactor: clean up form binding & validation (#38873) Clarify the "validation" and "error display" logic. All the copied&pasted `Validate` functions are removed. --- modules/structs/form.go | 28 +++ modules/structs/miscellaneous.go | 1 + modules/translation/i18n/i18n.go | 14 +- modules/translation/mock.go | 4 + modules/translation/translation.go | 11 +- modules/validation/binding_test.go | 8 +- modules/validation/glob_pattern_test.go | 2 - modules/validation/refname_test.go | 3 - modules/validation/regex_pattern_test.go | 2 - modules/validation/validurl_test.go | 5 - modules/web/middleware/binding.go | 66 ++---- modules/web/middleware/binding_test.go | 5 +- modules/web/router.go | 35 ++- routers/install/routes.go | 2 +- routers/web/auth/oauth2_provider.go | 12 - routers/web/repo/actions/view.go | 2 + routers/web/web.go | 268 +++++++++++------------ services/context/context.go | 1 - services/forms/admin.go | 40 +--- services/forms/auth_form.go | 16 +- services/forms/org.go | 27 +-- services/forms/package_form.go | 15 +- services/forms/repo_branch_form.go | 23 +- services/forms/repo_form.go | 218 ++++-------------- services/forms/repo_form_editor.go | 15 +- services/forms/repo_tag_form.go | 16 +- services/forms/runner.go | 16 +- services/forms/user_form.go | 178 +++------------ services/forms/user_form_auth_openid.go | 30 +-- tests/integration/auth_ldap_test.go | 5 +- 30 files changed, 331 insertions(+), 737 deletions(-) create mode 100644 modules/structs/form.go diff --git a/modules/structs/form.go b/modules/structs/form.go new file mode 100644 index 00000000000..4bbb48b9306 --- /dev/null +++ b/modules/structs/form.go @@ -0,0 +1,28 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package structs + +import ( + "net/http" + + "gitea.dev/modules/reqctx" + "gitea.dev/modules/translation/i18n" + + "gitea.com/go-chi/binding" +) + +// ValidateContext is a special context for form validation middleware +type ValidateContext struct { + Locale i18n.LocaleTranslation + Data reqctx.ContextData + Req *http.Request + Resp http.ResponseWriter +} + +type FormDefaultValidator struct{} + +func (FormDefaultValidator) Validate(ctx *ValidateContext, errs binding.Errors) binding.Errors { + // this default validator only needs to return the errs as is because the "binding" function has already validated + return errs +} diff --git a/modules/structs/miscellaneous.go b/modules/structs/miscellaneous.go index 293ba99579a..f9e7dbc3e5e 100644 --- a/modules/structs/miscellaneous.go +++ b/modules/structs/miscellaneous.go @@ -21,6 +21,7 @@ type SearchError struct { // MarkupOption markup options type MarkupOption struct { + FormDefaultValidator // Text markup to render // // in: body diff --git a/modules/translation/i18n/i18n.go b/modules/translation/i18n/i18n.go index fae41927dbf..a1da64f6a78 100644 --- a/modules/translation/i18n/i18n.go +++ b/modules/translation/i18n/i18n.go @@ -19,6 +19,18 @@ type Locale interface { HasKey(trKey string) bool } +// LocaleTranslation represents an interface to translation +type LocaleTranslation interface { + Language() string + HasKey(trKey string) bool + TrString(string, ...any) string + + Tr(key string, args ...any) template.HTML + TrN(cnt any, key1, keyN string, args ...any) template.HTML + + PrettyNumber(v any) string +} + // LocaleStore provides the functions common to all locale stores type LocaleStore interface { io.Closer @@ -31,7 +43,7 @@ type LocaleStore interface { Locale(langName string) (Locale, bool) // HasLang returns whether a given language is present in the store HasLang(langName string) bool - // AddLocaleByIni adds a new language to the store + // AddLocaleByJSON adds a new language to the store AddLocaleByJSON(langName, langDesc string, source, moreSource []byte) error } diff --git a/modules/translation/mock.go b/modules/translation/mock.go index 02b19d9583d..1ecfeb9bce0 100644 --- a/modules/translation/mock.go +++ b/modules/translation/mock.go @@ -14,6 +14,10 @@ type MockLocale struct { Lang, LangName string // these fields are used directly in templates: ctx.Locale.Lang } +func (l MockLocale) HasKey(trKey string) bool { + return true +} + var _ Locale = (*MockLocale)(nil) func (l MockLocale) Language() string { diff --git a/modules/translation/translation.go b/modules/translation/translation.go index f23845a6311..d54f55ea68b 100644 --- a/modules/translation/translation.go +++ b/modules/translation/translation.go @@ -25,16 +25,7 @@ type contextKey struct{} var ContextKey any = &contextKey{} -// Locale represents an interface to translation -type Locale interface { - Language() string - TrString(string, ...any) string - - Tr(key string, args ...any) template.HTML - TrN(cnt any, key1, keyN string, args ...any) template.HTML - - PrettyNumber(v any) string -} +type Locale = i18n.LocaleTranslation // LangType represents a lang type type LangType struct { diff --git a/modules/validation/binding_test.go b/modules/validation/binding_test.go index d30eb1bbb1c..ee893c516e8 100644 --- a/modules/validation/binding_test.go +++ b/modules/validation/binding_test.go @@ -37,13 +37,7 @@ func performValidationTest(t *testing.T, testCase validationTestCase) { m := chi.NewRouter() m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) { - actual := binding.Validate(req, testCase.data) - // see https://github.com/stretchr/testify/issues/435 - if actual == nil { - actual = binding.Errors{} - } - - assert.Equal(t, testCase.expectedErrors, actual) + assert.Equal(t, testCase.expectedErrors, binding.Validate(req, testCase.data)) }) req, err := http.NewRequest(http.MethodPost, testRoute, nil) diff --git a/modules/validation/glob_pattern_test.go b/modules/validation/glob_pattern_test.go index e22d131c617..094f307380d 100644 --- a/modules/validation/glob_pattern_test.go +++ b/modules/validation/glob_pattern_test.go @@ -29,14 +29,12 @@ func Test_GlobPatternValidation(t *testing.T) { data: TestForm{ GlobPattern: "", }, - expectedErrors: binding.Errors{}, }, { description: "Valid glob", data: TestForm{ GlobPattern: "{master,release*}", }, - expectedErrors: binding.Errors{}, }, { diff --git a/modules/validation/refname_test.go b/modules/validation/refname_test.go index 93703761cf9..f08aa8aa357 100644 --- a/modules/validation/refname_test.go +++ b/modules/validation/refname_test.go @@ -17,21 +17,18 @@ func Test_GitRefNameValidation(t *testing.T) { data: TestForm{ BranchName: "test", }, - expectedErrors: binding.Errors{}, }, { description: "Reference name contains single slash", data: TestForm{ BranchName: "feature/test", }, - expectedErrors: binding.Errors{}, }, { description: "Reference name has allowed special characters", data: TestForm{ BranchName: "debian/1%1.6.0-2", }, - expectedErrors: binding.Errors{}, }, { description: "Reference name contains backslash", diff --git a/modules/validation/regex_pattern_test.go b/modules/validation/regex_pattern_test.go index 80790a23b16..7f600da6866 100644 --- a/modules/validation/regex_pattern_test.go +++ b/modules/validation/regex_pattern_test.go @@ -26,14 +26,12 @@ func Test_RegexPatternValidation(t *testing.T) { data: TestForm{ RegexPattern: "", }, - expectedErrors: binding.Errors{}, }, { description: "Valid regex", data: TestForm{ RegexPattern: `(\d{1,3})+`, }, - expectedErrors: binding.Errors{}, }, { diff --git a/modules/validation/validurl_test.go b/modules/validation/validurl_test.go index ce4898b2716..52f6a191555 100644 --- a/modules/validation/validurl_test.go +++ b/modules/validation/validurl_test.go @@ -18,35 +18,30 @@ func Test_ValidURLValidation(t *testing.T) { data: TestForm{ URL: "", }, - expectedErrors: binding.Errors{}, }, { description: "URL without port", data: TestForm{ URL: "http://test.lan/", }, - expectedErrors: binding.Errors{}, }, { description: "URL with port", data: TestForm{ URL: "http://test.lan:3000/", }, - expectedErrors: binding.Errors{}, }, { description: "URL with IPv6 address without port", data: TestForm{ URL: "http://[::1]/", }, - expectedErrors: binding.Errors{}, }, { description: "URL with IPv6 address with port", data: TestForm{ URL: "http://[::1]:3000/", }, - expectedErrors: binding.Errors{}, }, { description: "Invalid URL", diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go index d189c0e088c..829cc699215 100644 --- a/modules/web/middleware/binding.go +++ b/modules/web/middleware/binding.go @@ -5,12 +5,11 @@ package middleware import ( - "net/http" "reflect" "strings" - "gitea.dev/modules/reqctx" "gitea.dev/modules/setting" + "gitea.dev/modules/structs" "gitea.dev/modules/translation" "gitea.dev/modules/util" "gitea.dev/modules/validation" @@ -18,17 +17,13 @@ import ( "gitea.com/go-chi/binding" ) -// ValidateContext is a special context for form validation middleware. It may be different from other contexts. -type ValidateContext struct { - Locale translation.Locale - Data reqctx.ContextData - Req *http.Request - Resp http.ResponseWriter -} +type ( + ValidateContext = structs.ValidateContext + FormDefaultValidator = structs.FormDefaultValidator +) -// Form form binding interface type Form interface { - binding.Validator + Validate(ctx *ValidateContext, errs binding.Errors) binding.Errors } func init() { @@ -84,9 +79,17 @@ func getFieldDisplayNameForMessage(f Form, l translation.Locale, fieldNames []st typ = typ.Elem() } - field, fieldExists := typ.FieldByName(fieldNames[0]) + fieldName := fieldNames[0] + field, fieldExists := typ.FieldByName(fieldName) if !fieldExists { - return field, false, "" + for tryField := range typ.Fields() { + if util.ToSnakeCase(tryField.Name) == fieldName || tryField.Tag.Get("form") == fieldName { + field, fieldExists = tryField, true + } + } + if !fieldExists { + return field, false, "" + } } if field.Tag.Get("form") == "-" { @@ -95,8 +98,9 @@ func getFieldDisplayNameForMessage(f Form, l translation.Locale, fieldNames []st trKeyFallback := "form." + field.Name trKey := util.IfZero(field.Tag.Get("locale"), trKeyFallback) - displayName = l.TrString(trKey) - if displayName == trKeyFallback { + if l.HasKey(trKey) { + displayName = l.TrString(trKey) + } else { displayName = field.Name } return field, true, displayName @@ -156,7 +160,7 @@ func BuildValidationErrorForUser(f Form, l translation.Locale, bindingErrs bindi case validation.ErrInvalidBadgeSlug: errorMessage = l.TrString("form.invalid_slug_error", fieldDisplayName) default: - setting.PanicInDevOrTesting("unknown binding error classification: %v", classification) + setting.PanicInDevOrTesting("unknown binding error classification for field %T.%s: %v, err: %s", f, errorFieldName, classification, bindingErrMsg) var msg string if classification != "" && bindingErrMsg != "" { msg = classification + ": " + bindingErrMsg @@ -171,33 +175,3 @@ func BuildValidationErrorForUser(f Form, l translation.Locale, bindingErrs bindi } return errorMessage, errorFieldName, fieldNames } - -type contextKeySkipTmplFormValidationErrorType struct{} - -var contextKeySkipTmplFormValidationError contextKeySkipTmplFormValidationErrorType - -func SkipTmplFormValidationError(ctx reqctx.RequestContext) { - ctx.SetContextValue(contextKeySkipTmplFormValidationError, true) -} - -func Validate(ctx *ValidateContext, errs binding.Errors, f Form) binding.Errors { - if ctx.Req.Context().Value(contextKeySkipTmplFormValidationError) == true { - // if it is not using tmpl-based validation error handling, just return the errors - // for example: when using "form-fetch-action", the validation error can be handled by GetFetchActionForm - return errs - } - errorMessage, errorFieldName, _ := BuildValidationErrorForUser(f, ctx.Locale, errs) - if errorMessage == "" { - return errs - } - - // Legacy template error handling: try to restore the form's values as much as possible, - // especially for RenderWithErrDeprecated to re-render the form with errors. - AssignForm(f, ctx.Data) - ctx.Data["HasError"] = true - ctx.Data["ErrorMsg"] = errorMessage - if errorFieldName != "" { - ctx.Data["Err_"+errorFieldName] = true - } - return errs -} diff --git a/modules/web/middleware/binding_test.go b/modules/web/middleware/binding_test.go index d3920254277..bebe5fdea3d 100644 --- a/modules/web/middleware/binding_test.go +++ b/modules/web/middleware/binding_test.go @@ -15,17 +15,16 @@ import ( ) type testRangeForm struct { + FormDefaultValidator Hours int `binding:"Range(0,1000)"` } -func (f *testRangeForm) Validate(_ *http.Request, errs binding.Errors) binding.Errors { return errs } - func TestBuildValidationErrorForUser(t *testing.T) { // an out-of-range value must reach its own message instead of the panicking "default" branch form := &testRangeForm{Hours: 2000} errs := binding.Validate(httptest.NewRequest(http.MethodPost, "/", nil), form) errorMessage, errorFieldName, fieldNames := BuildValidationErrorForUser(form, translation.MockLocale{}, errs) - assert.Equal(t, "form.range_error:Hours,0,1000", errorMessage) + assert.Equal(t, "form.range_error:form.Hours,0,1000", errorMessage) assert.Equal(t, "Hours", errorFieldName) assert.Equal(t, []string{"Hours"}, fieldNames) } diff --git a/modules/web/router.go b/modules/web/router.go index 1b9ab534561..2e3a90f1cfc 100644 --- a/modules/web/router.go +++ b/modules/web/router.go @@ -14,6 +14,7 @@ import ( "gitea.dev/modules/public" "gitea.dev/modules/reqctx" "gitea.dev/modules/setting" + "gitea.dev/modules/translation" "gitea.dev/modules/web/middleware" "gitea.dev/modules/web/types" @@ -21,14 +22,34 @@ import ( "github.com/go-chi/chi/v5" ) -// Bind binding an obj to a handler's context data -func Bind[T any](_ T) http.HandlerFunc { +// Bind binding the request form to a form object and assign context data +func Bind[T interface { + *E + middleware.Form +}, E any]() http.HandlerFunc { return func(resp http.ResponseWriter, req *http.Request) { - theObj := new(T) // create a new form obj for every request but not use obj directly - data := middleware.GetContextData(req.Context()) - _ = binding.Bind(req, theObj) // no need to handle "errs" here, the errors are handled in our middleware.Validate (binding.go) - SetForm(data, theObj) - middleware.AssignForm(theObj, data) + ctx := reqctx.FromContext(req.Context()) + data := ctx.GetData() + locale := ctx.Value(translation.ContextKey).(translation.Locale) //nolint:forcetypeassert // must exist + + obj := new(E) + var form T = obj + vctx := &middleware.ValidateContext{Locale: locale, Data: data, Req: req, Resp: resp} + errs := binding.Bind(req, obj) + errs = form.Validate(vctx, errs) + SetForm(data, obj) + + // Legacy template error handling: try to restore the form's values as much as possible, + // especially for RenderWithErrDeprecated to re-render the form with errors. + middleware.AssignForm(obj, data) + errorMessage, errorFieldName, _ := middleware.BuildValidationErrorForUser(form, locale, errs) + if errorMessage != "" { + data["HasError"] = true + data["ErrorMsg"] = errorMessage + if errorFieldName != "" { + data["Err_"+errorFieldName] = true + } + } } } diff --git a/routers/install/routes.go b/routers/install/routes.go index f650c695729..14f3c4ff55a 100644 --- a/routers/install/routes.go +++ b/routers/install/routes.go @@ -28,7 +28,7 @@ func Routes() *web.Router { r.AfterRouting(common.MustInitSessioner(), installContexter()) r.Get("/", Install) // it must be on the root, because the "install.js" use the window.location to replace the "localhost" AppURL - r.Post("/", web.Bind(forms.InstallForm{}), SubmitInstall) + r.Post("/", web.Bind[*forms.InstallForm](), SubmitInstall) r.Get("/post-install", InstallDone) r.Get("/-/web-theme/list", misc.WebThemeList) diff --git a/routers/web/auth/oauth2_provider.go b/routers/web/auth/oauth2_provider.go index a40aa19c209..8da6cd34d66 100644 --- a/routers/web/auth/oauth2_provider.go +++ b/routers/web/auth/oauth2_provider.go @@ -11,7 +11,6 @@ import ( "net/http" "net/url" "strconv" - "strings" "gitea.dev/models/auth" user_model "gitea.dev/models/user" @@ -26,7 +25,6 @@ import ( "gitea.dev/services/forms" "gitea.dev/services/oauth2_provider" - "gitea.com/go-chi/binding" jwt "github.com/golang-jwt/jwt/v5" ) @@ -225,16 +223,6 @@ func AuthorizeOAuth(ctx *context.Context) { if !oauthDoerAuthorizePreCheck(ctx, form.State) { return } - errs := binding.Errors{} - errs = form.Validate(ctx.Req, errs) - if len(errs) > 0 { - var errstring strings.Builder - for _, e := range errs { - errstring.WriteString(e.Error() + "\n") - } - ctx.ServerError("AuthorizeOAuth: Validate: ", fmt.Errorf("errors occurred during validation: %s", errstring.String())) - return - } app, err := auth.GetOAuth2ApplicationByClientID(ctx, form.ClientID) if err != nil { diff --git a/routers/web/repo/actions/view.go b/routers/web/repo/actions/view.go index bae6d1c0269..773176b0751 100644 --- a/routers/web/repo/actions/view.go +++ b/routers/web/repo/actions/view.go @@ -39,6 +39,7 @@ import ( "gitea.dev/modules/translation" "gitea.dev/modules/util" "gitea.dev/modules/web" + "gitea.dev/modules/web/middleware" "gitea.dev/routers/common" actions_service "gitea.dev/services/actions" context_module "gitea.dev/services/context" @@ -277,6 +278,7 @@ type LogCursor struct { } type ViewRequest struct { + middleware.FormDefaultValidator LogCursors []LogCursor `json:"logCursors"` } diff --git a/routers/web/web.go b/routers/web/web.go index 8e986d8dac3..91fb2c93974 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -329,9 +329,9 @@ var optSignInFromAnyOrigin = verifyAuthWithOptions(&common.VerifyOptions{Disable func addProjectBoardRoutes(m *web.Router) { // TODO: improper name. Others are "delete project", "edit project", but this one is "move columns" m.Post("/move", project.MoveColumns) - m.Post("/columns/new", web.Bind(forms.EditProjectColumnForm{}), project.AddColumnToProjectPost) + m.Post("/columns/new", web.Bind[*forms.EditProjectColumnForm](), project.AddColumnToProjectPost) m.Group("/{columnID}", func() { - m.Put("", web.Bind(forms.EditProjectColumnForm{}), project.EditProjectColumn) + m.Put("", web.Bind[*forms.EditProjectColumnForm](), project.EditProjectColumn) m.Delete("", project.DeleteProjectColumn) m.Post("/default", project.SetDefaultProjectColumn) m.Post("/move", project.MoveIssues) @@ -458,38 +458,38 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { addWebhookAddRoutes := func() { m.Get("/{type}/new", repo_setting.WebhooksNew) - m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksNewPost) - m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksNewPost) - m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksNewPost) - m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksNewPost) - m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksNewPost) - m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksNewPost) - m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksNewPost) - m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksNewPost) - m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksNewPost) - m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksNewPost) - m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksNewPost) + m.Post("/gitea/new", web.Bind[*forms.NewWebhookForm](), repo_setting.GiteaHooksNewPost) + m.Post("/gogs/new", web.Bind[*forms.NewGogshookForm](), repo_setting.GogsHooksNewPost) + m.Post("/slack/new", web.Bind[*forms.NewSlackHookForm](), repo_setting.SlackHooksNewPost) + m.Post("/discord/new", web.Bind[*forms.NewDiscordHookForm](), repo_setting.DiscordHooksNewPost) + m.Post("/dingtalk/new", web.Bind[*forms.NewDingtalkHookForm](), repo_setting.DingtalkHooksNewPost) + m.Post("/telegram/new", web.Bind[*forms.NewTelegramHookForm](), repo_setting.TelegramHooksNewPost) + m.Post("/matrix/new", web.Bind[*forms.NewMatrixHookForm](), repo_setting.MatrixHooksNewPost) + m.Post("/msteams/new", web.Bind[*forms.NewMSTeamsHookForm](), repo_setting.MSTeamsHooksNewPost) + m.Post("/feishu/new", web.Bind[*forms.NewFeishuHookForm](), repo_setting.FeishuHooksNewPost) + m.Post("/wechatwork/new", web.Bind[*forms.NewWechatWorkHookForm](), repo_setting.WechatworkHooksNewPost) + m.Post("/packagist/new", web.Bind[*forms.NewPackagistHookForm](), repo_setting.PackagistHooksNewPost) } addWebhookEditRoutes := func() { - m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksEditPost) - m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksEditPost) - m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksEditPost) - m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksEditPost) - m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksEditPost) - m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksEditPost) - m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksEditPost) - m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksEditPost) - m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksEditPost) - m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksEditPost) - m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksEditPost) + m.Post("/gitea/{id}", web.Bind[*forms.NewWebhookForm](), repo_setting.GiteaHooksEditPost) + m.Post("/gogs/{id}", web.Bind[*forms.NewGogshookForm](), repo_setting.GogsHooksEditPost) + m.Post("/slack/{id}", web.Bind[*forms.NewSlackHookForm](), repo_setting.SlackHooksEditPost) + m.Post("/discord/{id}", web.Bind[*forms.NewDiscordHookForm](), repo_setting.DiscordHooksEditPost) + m.Post("/dingtalk/{id}", web.Bind[*forms.NewDingtalkHookForm](), repo_setting.DingtalkHooksEditPost) + m.Post("/telegram/{id}", web.Bind[*forms.NewTelegramHookForm](), repo_setting.TelegramHooksEditPost) + m.Post("/matrix/{id}", web.Bind[*forms.NewMatrixHookForm](), repo_setting.MatrixHooksEditPost) + m.Post("/msteams/{id}", web.Bind[*forms.NewMSTeamsHookForm](), repo_setting.MSTeamsHooksEditPost) + m.Post("/feishu/{id}", web.Bind[*forms.NewFeishuHookForm](), repo_setting.FeishuHooksEditPost) + m.Post("/wechatwork/{id}", web.Bind[*forms.NewWechatWorkHookForm](), repo_setting.WechatworkHooksEditPost) + m.Post("/packagist/{id}", web.Bind[*forms.NewPackagistHookForm](), repo_setting.PackagistHooksEditPost) } addSettingsVariablesRoutes := func() { m.Group("/variables", func() { m.Get("", shared_actions.Variables) - m.Post("/new", web.Bind(forms.EditVariableForm{}), shared_actions.VariableCreate) - m.Post("/{variable_id}/edit", web.Bind(forms.EditVariableForm{}), shared_actions.VariableUpdate) + m.Post("/new", web.Bind[*forms.EditVariableForm](), shared_actions.VariableCreate) + m.Post("/{variable_id}/edit", web.Bind[*forms.EditVariableForm](), shared_actions.VariableUpdate) m.Post("/{variable_id}/delete", shared_actions.VariableDelete) }) } @@ -497,7 +497,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { addSettingsSecretsRoutes := func() { m.Group("/secrets", func() { m.Get("", repo_setting.Secrets) - m.Post("", web.Bind(forms.AddSecretForm{}), repo_setting.SecretsPost) + m.Post("", web.Bind[*forms.AddSecretForm](), repo_setting.SecretsPost) m.Post("/delete", repo_setting.SecretsDelete) }) } @@ -506,7 +506,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/runners", func() { m.Get("", shared_actions.Runners) m.Combo("/{runnerid}").Get(shared_actions.RunnersEdit). - Post(web.Bind(forms.EditRunnerForm{}), shared_actions.RunnersEditPost) + Post(web.Bind[*forms.EditRunnerForm](), shared_actions.RunnersEditPost) m.Post("/{runnerid}/update-runner", shared_actions.RunnerUpdatePost) m.Post("/{runnerid}/delete", shared_actions.RunnerDeletePost) m.Post("/reset_registration_token", shared_actions.ResetRunnerRegistrationToken) @@ -540,7 +540,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Methods("GET, HEAD", "/*", public.FileHandlerFunc()) }, optionsCorsHandler()) - m.Post("/-/markup", reqSignIn, web.Bind(structs.MarkupOption{}), misc.Markup) + m.Post("/-/markup", reqSignIn, web.Bind[*structs.MarkupOption](), misc.Markup) m.Post("/-/web-banner/dismiss", misc.WebBannerDismiss) m.Get("/-/web-theme/list", misc.WebThemeList) m.Post("/-/web-theme/apply", optSignIn, misc.WebThemeApply) @@ -575,32 +575,32 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // "user/login" doesn't need signOut, then logged-in users can still access this route for redirection purposes by "/user/login?redirec_to=..." m.Get("/user/login", auth.SignIn) m.Group("/user", func() { - m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost) + m.Post("/login", web.Bind[*forms.SignInForm](), auth.SignInPost) m.Group("", func() { m.Combo("/login/openid"). Get(auth.SignInOpenID). - Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost) + Post(web.Bind[*forms.SignInOpenIDForm](), auth.SignInOpenIDPost) }, openIDSignInEnabled) m.Group("/openid", func() { m.Combo("/connect"). Get(auth.ConnectOpenID). - Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost) + Post(web.Bind[*forms.ConnectOpenIDForm](), auth.ConnectOpenIDPost) m.Group("/register", func() { m.Combo(""). Get(auth.RegisterOpenID, openIDSignUpEnabled). - Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost) + Post(web.Bind[*forms.SignUpOpenIDForm](), auth.RegisterOpenIDPost) }, openIDSignUpEnabled) }, openIDSignInEnabled) m.Get("/sign_up", auth.SignUp) - m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost) + m.Post("/sign_up", web.Bind[*forms.RegisterForm](), auth.SignUpPost) m.Get("/link_account", auth.LinkAccount) - m.Post("/link_account_signin", web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn) - m.Post("/link_account_signup", web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister) + m.Post("/link_account_signin", web.Bind[*forms.SignInForm](), auth.LinkAccountPostSignIn) + m.Post("/link_account_signup", web.Bind[*forms.RegisterForm](), auth.LinkAccountPostRegister) m.Group("/two_factor", func() { m.Get("", auth.TwoFactor) - m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost) + m.Post("", web.Bind[*forms.TwoFactorAuthForm](), auth.TwoFactorPost) m.Get("/scratch", auth.TwoFactorScratch) - m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost) + m.Post("/scratch", web.Bind[*forms.TwoFactorScratchAuthForm](), auth.TwoFactorScratchPost) }) m.Group("/webauthn", func() { m.Get("", auth.WebAuthn) @@ -615,39 +615,39 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/login/oauth", func() { m.Group("", func() { - m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) - m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth) + m.Get("/authorize", web.Bind[*forms.AuthorizationForm](), auth.AuthorizeOAuth) + m.Post("/grant", web.Bind[*forms.GrantApplicationForm](), auth.GrantApplicationOAuth) // TODO manage redirection - m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) + m.Post("/authorize", web.Bind[*forms.AuthorizationForm](), auth.AuthorizeOAuth) }, reqSignIn) m.Group("", func() { m.Methods("GET, POST, OPTIONS", "/userinfo", auth.InfoOAuth) - m.Methods("POST, OPTIONS", "/access_token", web.Bind(forms.AccessTokenForm{}), auth.AccessTokenOAuth) + m.Methods("POST, OPTIONS", "/access_token", web.Bind[*forms.AccessTokenForm](), auth.AccessTokenOAuth) m.Methods("GET, OPTIONS", "/keys", auth.OIDCKeys) - m.Methods("POST, OPTIONS", "/introspect", web.Bind(forms.IntrospectTokenForm{}), auth.IntrospectOAuth) + m.Methods("POST, OPTIONS", "/introspect", web.Bind[*forms.IntrospectTokenForm](), auth.IntrospectOAuth) }, optionsCorsHandler(), webAuth.AllowOAuth2, optSignInFromAnyOrigin) }, oauth2Enabled) m.Group("/user/settings", func() { m.Get("", user_setting.Profile) - m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost) + m.Post("", web.Bind[*forms.UpdateProfileForm](), user_setting.ProfilePost) m.Post("/update_preferences", user_setting.UpdatePreferences) m.Get("/change_password", auth.MustChangePassword) - m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost) - m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost) + m.Post("/change_password", web.Bind[*forms.MustChangePasswordForm](), auth.MustChangePasswordPost) + m.Post("/avatar", web.Bind[*forms.AvatarForm](), user_setting.AvatarPost) m.Post("/avatar/delete", user_setting.DeleteAvatar) m.Group("/account", func() { - m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost) - m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost) + m.Combo("").Get(user_setting.Account).Post(web.Bind[*forms.ChangePasswordForm](), user_setting.AccountPost) + m.Post("/email", web.Bind[*forms.AddEmailForm](), user_setting.EmailPost) m.Post("/email/delete", user_setting.DeleteEmail) m.Post("/delete", user_setting.DeleteAccount) }) m.Group("/appearance", func() { m.Get("", user_setting.Appearance) - m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang) + m.Post("/language", web.Bind[*forms.UpdateLanguageForm](), user_setting.UpdateUserLang) m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments) - m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost) + m.Post("/theme", web.Bind[*forms.UpdateThemeForm](), user_setting.UpdateUIThemePost) }) m.Group("/notifications", func() { m.Get("", user_setting.Notifications) @@ -660,15 +660,15 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor) m.Post("/disable", security.DisableTwoFactor) m.Get("/enroll", security.EnrollTwoFactor) - m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost) + m.Post("/enroll", web.Bind[*forms.TwoFactorAuthForm](), security.EnrollTwoFactorPost) }) m.Group("/webauthn", func() { - m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister) + m.Post("/request_register", web.Bind[*forms.WebauthnRegistrationForm](), security.WebAuthnRegister) m.Post("/register", security.WebauthnRegisterPost) m.Post("/delete", security.WebauthnDelete) }) m.Group("/openid", func() { - m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost) + m.Post("", web.Bind[*forms.AddOpenIDForm](), security.OpenIDPost) m.Post("/delete", security.DeleteOpenID) m.Post("/toggle_visibility", security.ToggleOpenIDVisibility) }, openIDSignInEnabled) @@ -679,32 +679,32 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // oauth2 applications m.Group("/oauth2", func() { m.Get("/{id}", user_setting.OAuth2ApplicationShow) - m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit) + m.Post("/{id}", web.Bind[*forms.EditOAuth2ApplicationForm](), user_setting.OAuthApplicationsEdit) m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret) - m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost) + m.Post("", web.Bind[*forms.EditOAuth2ApplicationForm](), user_setting.OAuthApplicationsPost) m.Post("/{id}/delete", user_setting.DeleteOAuth2Application) m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant) }, oauth2Enabled) // access token applications m.Combo("").Get(user_setting.Applications). - Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost) + Post(web.Bind[*forms.NewAccessTokenForm](), user_setting.ApplicationsPost) m.Post("/delete", user_setting.DeleteApplication) }) m.Combo("/keys").Get(user_setting.Keys). - Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost) + Post(web.Bind[*forms.AddKeyForm](), user_setting.KeysPost) m.Post("/keys/delete", user_setting.DeleteKey) m.Group("/packages", func() { m.Get("", user_setting.Packages) m.Group("/rules", func() { m.Group("/add", func() { m.Get("", user_setting.PackagesRuleAdd) - m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost) + m.Post("", web.Bind[*forms.PackageCleanupRuleForm](), user_setting.PackagesRuleAddPost) }) m.Group("/{id}", func() { m.Get("", user_setting.PackagesRuleEdit) - m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost) + m.Post("", web.Bind[*forms.PackageCleanupRuleForm](), user_setting.PackagesRuleEditPost) m.Get("/preview", user_setting.PackagesRulePreview) }) }) @@ -744,7 +744,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/blocked_users", func() { m.Get("", user_setting.BlockedUsers) - m.Post("", web.Bind(forms.BlockUserForm{}), user_setting.BlockedUsersPost) + m.Post("", web.Bind[*forms.BlockUserForm](), user_setting.BlockedUsersPost) }) }, reqSignIn, user_setting.SettingsCtxData) @@ -775,7 +775,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/-/admin", func() { m.Get("", admin.Dashboard) m.Get("/system_status", admin.SystemStatus) - m.Post("", web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost) + m.Post("", web.Bind[*forms.AdminDashboardForm](), admin.DashboardPost) m.Get("/self_check", admin.SelfCheck) m.Post("/self_check", admin.SelfCheckPost) @@ -805,20 +805,20 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/users", func() { m.Get("", admin.Users) - m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost) + m.Combo("/new").Get(admin.NewUser).Post(web.Bind[*forms.AdminCreateUserForm](), admin.NewUserPost) m.Get("/{userid}", admin.ViewUser) - m.Combo("/{userid}/edit").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost) + m.Combo("/{userid}/edit").Get(admin.EditUser).Post(web.Bind[*forms.AdminEditUserForm](), admin.EditUserPost) m.Post("/{userid}/impersonate", admin.ImpersonateUser) m.Post("/{userid}/delete", admin.DeleteUser) - m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost) + m.Post("/{userid}/avatar", web.Bind[*forms.AvatarForm](), admin.AvatarPost) m.Post("/{userid}/avatar/delete", admin.DeleteAvatar) }) m.Group("/badges", func() { m.Get("", admin.Badges) - m.Combo("/new").Get(admin.NewBadge).Post(web.Bind(forms.AdminCreateBadgeForm{}), admin.NewBadgePost) + m.Combo("/new").Get(admin.NewBadge).Post(web.Bind[*forms.AdminCreateBadgeForm](), admin.NewBadgePost) m.Get("/slug/{badge_slug}", admin.ViewBadge) - m.Combo("/slug/{badge_slug}/edit").Get(admin.EditBadge).Post(web.Bind(forms.AdminEditBadgeForm{}), admin.EditBadgePost) + m.Combo("/slug/{badge_slug}/edit").Get(admin.EditBadge).Post(web.Bind[*forms.AdminEditBadgeForm](), admin.EditBadgePost) m.Post("/slug/{badge_slug}/delete", admin.DeleteBadge) m.Combo("/slug/{badge_slug}/users").Get(admin.BadgeUsers).Post(admin.BadgeUsersPost) m.Post("/slug/{badge_slug}/users/delete", admin.DeleteBadgeUser) @@ -862,9 +862,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/auths", func() { m.Get("", admin.Authentications) - m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost) + m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind[*forms.AuthenticationForm](), admin.NewAuthSourcePost) m.Combo("/{authid}").Get(admin.EditAuthSource). - Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost) + Post(web.Bind[*forms.AuthenticationForm](), admin.EditAuthSourcePost) m.Post("/{authid}/delete", admin.DeleteAuthSource) }) @@ -876,9 +876,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/applications", func() { m.Get("", admin.Applications) - m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost) + m.Post("/oauth2", web.Bind[*forms.EditOAuth2ApplicationForm](), admin.ApplicationsPost) m.Group("/oauth2/{id}", func() { - m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost) + m.Combo("").Get(admin.EditApplication).Post(web.Bind[*forms.EditOAuth2ApplicationForm](), admin.EditApplicationPost) m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret) m.Post("/delete", admin.DeleteApplication) }) @@ -958,7 +958,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/org", func() { m.Group("", func() { m.Get("/create", org.Create) - m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost) + m.Post("/create", web.Bind[*forms.CreateOrgForm](), org.CreatePost) }) m.Group("/invite/{token}", func() { @@ -997,23 +997,23 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // require owner permission m.Group("/{org}", func() { m.Get("/teams/new", org.NewTeam) - m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost) + m.Post("/teams/new", web.Bind[*forms.CreateTeamForm](), org.NewTeamPost) m.Get("/teams/{team}/edit", org.EditTeam) - m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost) + m.Post("/teams/{team}/edit", web.Bind[*forms.CreateTeamForm](), org.EditTeamPost) m.Post("/teams/{team}/delete", org.DeleteTeam) m.Get("/worktime", context.OrgAssignment(context.OrgAssignmentOptions{RequireOwner: true}), org.Worktime) m.Group("/settings", func() { m.Combo("").Get(org.Settings). - Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost) - m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar) + Post(web.Bind[*forms.UpdateOrgSettingForm](), org.SettingsPost) + m.Post("/avatar", web.Bind[*forms.AvatarForm](), org.SettingsAvatar) m.Post("/avatar/delete", org.SettingsDeleteAvatar) m.Group("/applications", func() { m.Get("", org.Applications) - m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost) + m.Post("/oauth2", web.Bind[*forms.EditOAuth2ApplicationForm](), org.OAuthApplicationsPost) m.Group("/oauth2/{id}", func() { - m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit) + m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind[*forms.EditOAuth2ApplicationForm](), org.OAuth2ApplicationEdit) m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret) m.Post("/delete", org.DeleteOAuth2Application) }) @@ -1032,10 +1032,10 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/labels", func() { m.Get("", org.RetrieveLabels, org.Labels) - m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel) - m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel) + m.Post("/new", web.Bind[*forms.CreateLabelForm](), org.NewLabel) + m.Post("/edit", web.Bind[*forms.CreateLabelForm](), org.UpdateLabel) m.Post("/delete", org.DeleteLabel) - m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels) + m.Post("/initialize", web.Bind[*forms.InitializeLabelsForm](), org.InitializeLabels) }) m.Group("/actions", func() { @@ -1050,7 +1050,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { addSettingsScopedWorkflowsRoutes() }, actions.MustEnableActions) - m.Post("/rename", web.Bind(forms.RenameOrgForm{}), org.SettingsRenamePost) + m.Post("/rename", web.Bind[*forms.RenameOrgForm](), org.SettingsRenamePost) m.Post("/delete", org.SettingsDeleteOrgPost) m.Post("/visibility", org.SettingsChangeVisibilityPost) @@ -1059,11 +1059,11 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/rules", func() { m.Group("/add", func() { m.Get("", org.PackagesRuleAdd) - m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost) + m.Post("", web.Bind[*forms.PackageCleanupRuleForm](), org.PackagesRuleAddPost) }) m.Group("/{id}", func() { m.Get("", org.PackagesRuleEdit) - m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost) + m.Post("", web.Bind[*forms.PackageCleanupRuleForm](), org.PackagesRuleEditPost) m.Get("/preview", org.PackagesRulePreview) }) }) @@ -1075,7 +1075,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/blocked_users", func() { m.Get("", org.BlockedUsers) - m.Post("", web.Bind(forms.BlockUserForm{}), org.BlockedUsersPost) + m.Post("", web.Bind[*forms.BlockUserForm](), org.BlockedUsersPost) }) }, ctxDataSet(reqctx.ContextData{"EnableOAuth2": setting.OAuth2.Enabled, "EnablePackages": setting.Packages.Enabled, "PageIsOrgSettings": true})) }, context.OrgAssignment(context.OrgAssignmentOptions{RequireOwner: true})) @@ -1084,9 +1084,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/repo", func() { m.Get("/create", repo.Create) - m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost) + m.Post("/create", web.Bind[*forms.CreateRepoForm](), repo.CreatePost) m.Get("/migrate", repo.Migrate) - m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost) + m.Post("/migrate", web.Bind[*forms.MigrateRepoForm](), repo.MigratePost) m.Get("/search", repo.SearchRepo) }, reqSignIn) // end "/repo": create, migrate, search @@ -1111,7 +1111,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { }) m.Group("/settings/{type}/{name}", func() { m.Get("", user.PackageSettings) - m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost) + m.Post("", web.Bind[*forms.PackageSettingForm](), user.PackageSettingsPost) }, reqPackageAccess(perm.AccessModeWrite)) }, context.PackageAssignment(), reqPackageAccess(perm.AccessModeRead)) } @@ -1129,12 +1129,12 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true)) m.Group("", func() { m.Get("/new", org.RenderNewProject) - m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost) + m.Post("/new", web.Bind[*forms.CreateProjectForm](), org.NewProjectPost) m.Group("/{id}", func() { m.Post("/delete", org.DeleteProject) m.Get("/edit", org.RenderEditProject) - m.Post("/edit", web.Bind(forms.CreateProjectForm{}), org.EditProjectPost) + m.Post("/edit", web.Bind[*forms.CreateProjectForm](), org.EditProjectPost) m.Post("/{action:open|close}", org.ChangeProjectStatus) addProjectBoardRoutes(m) @@ -1168,9 +1168,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/{username}/{reponame}/settings", func() { m.Group("", func() { m.Combo("").Get(repo_setting.Settings). - Post(web.Bind(forms.RepoSettingForm{}), repo_setting.SettingsPost) + Post(web.Bind[*forms.RepoSettingForm](), repo_setting.SettingsPost) }, repo_setting.SettingsCtxData) - m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo_setting.SettingsAvatar) + m.Post("/avatar", web.Bind[*forms.AvatarForm](), repo_setting.SettingsAvatar) m.Post("/avatar/delete", repo_setting.SettingsDeleteAvatar) m.Combo("/public_access").Get(repo_setting.PublicAccess).Post(repo_setting.PublicAccessPost) @@ -1192,17 +1192,17 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/branches", func() { m.Get("/", repo_setting.ProtectedBranchRules) m.Combo("/edit").Get(repo_setting.SettingsProtectedBranch). - Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.SettingsProtectedBranchPost) + Post(web.Bind[*forms.ProtectBranchForm](), context.RepoMustNotBeArchived(), repo_setting.SettingsProtectedBranchPost) m.Post("/{id}/delete", repo_setting.DeleteProtectedBranchRulePost) m.Post("/priority", context.RepoMustNotBeArchived(), repo_setting.UpdateBranchProtectionPriories) }) m.Group("/tags", func() { m.Get("", repo_setting.ProtectedTags) - m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.NewProtectedTagPost) + m.Post("", web.Bind[*forms.ProtectTagForm](), context.RepoMustNotBeArchived(), repo_setting.NewProtectedTagPost) m.Post("/delete", context.RepoMustNotBeArchived(), repo_setting.DeleteProtectedTagPost) m.Get("/{id}", repo_setting.EditProtectedTag) - m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.EditProtectedTagPost) + m.Post("/{id}", web.Bind[*forms.ProtectTagForm](), context.RepoMustNotBeArchived(), repo_setting.EditProtectedTagPost) }) m.Group("/hooks/git", func() { @@ -1273,7 +1273,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // user/org home, including rss feeds like "/{username}/{reponame}.rss" m.Get("/{username}/{reponame}", optSignIn, webAuth.AllowBasic, context.RepoAssignment, context.RepoRefByType(git.RefTypeBranch), repo.SetEditorconfigIfExists, repo.Home) - m.Post("/{username}/{reponame}/markup", optSignIn, context.RepoAssignment, reqUnitsWithMarkdown, web.Bind(structs.MarkupOption{}), misc.Markup) + m.Post("/{username}/{reponame}/markup", optSignIn, context.RepoAssignment, reqUnitsWithMarkdown, web.Bind[*structs.MarkupOption](), misc.Markup) m.Group("/{username}/{reponame}", func() { m.Group("/tree-list", func() { @@ -1291,7 +1291,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { g.MatchPath("GET", "/.diff", repo.MustBeNotEmpty, repo.DownloadCompareDiff) g.MatchPath("GET", "/.patch", repo.MustBeNotEmpty, repo.DownloadComparePatch) g.MatchPath("GET", "/<*:*>", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff) - g.MatchPath("POST", "/<*:*>", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists, reqSignIn, context.RepoMustNotBeArchived(), reqUnitPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost) + g.MatchPath("POST", "/<*:*>", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists, reqSignIn, context.RepoMustNotBeArchived(), reqUnitPullsReader, repo.MustAllowPulls, web.Bind[*forms.CreateIssueForm](), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost) }) m.Get("/pulls/new/*", repo.PullsNewRedirect) }, optSignIn, context.RepoAssignment, reqUnitCodeReader) @@ -1335,7 +1335,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/issues", func() { m.Group("/new", func() { m.Combo("").Get(repo.NewIssue). - Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost) + Post(web.Bind[*forms.CreateIssueForm](), repo.NewIssuePost) m.Get("/choose", repo.NewIssueChooseTemplate) }) m.Get("/search", repo.SearchRepoIssuesJSON) @@ -1355,9 +1355,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Post("/add", repo.AddDependency) m.Post("/delete", repo.RemoveDependency) }) - m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment) + m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind[*forms.CreateCommentForm](), repo.NewComment) m.Group("/times", func() { - m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually) + m.Post("/add", web.Bind[*forms.AddTimeManuallyForm](), repo.AddTimeManually) m.Post("/{timeid}/delete", repo.DeleteTime) m.Group("/stopwatch", func() { m.Post("/start", repo.IssueStartStopwatch) @@ -1366,8 +1366,8 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { }) }) m.Post("/time_estimate", repo.UpdateIssueTimeEstimate) - m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction) - m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue) + m.Post("/reactions/{action}", web.Bind[*forms.ReactionForm](), repo.ChangeIssueReaction) + m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind[*forms.IssueLockForm](), repo.LockIssue) m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue) m.Post("/delete", reqRepoAdmin, repo.DeleteIssue) m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory) @@ -1393,21 +1393,21 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/comments/{id}", func() { m.Post("", repo.UpdateCommentContent) m.Post("/delete", repo.DeleteComment) - m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction) + m.Post("/reactions/{action}", web.Bind[*forms.ReactionForm](), repo.ChangeCommentReaction) }, reqRepoIssuesOrPullsReader) // edit issue/pull comment m.Group("/labels", func() { - m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel) - m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel) + m.Post("/new", web.Bind[*forms.CreateLabelForm](), repo.NewLabel) + m.Post("/edit", web.Bind[*forms.CreateLabelForm](), repo.UpdateLabel) m.Post("/delete", repo.DeleteLabel) - m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels) + m.Post("/initialize", web.Bind[*forms.InitializeLabelsForm](), repo.InitializeLabels) }, reqRepoIssuesOrPullsWriter) m.Group("/milestones", func() { m.Combo("/new").Get(repo.NewMilestone). - Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost) + Post(web.Bind[*forms.CreateMilestoneForm](), repo.NewMilestonePost) m.Get("/{id}/edit", repo.EditMilestone) - m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost) + m.Post("/{id}/edit", web.Bind[*forms.CreateMilestoneForm](), repo.EditMilestonePost) m.Post("/{id}/{action}", repo.ChangeMilestoneStatus) m.Post("/delete", repo.DeleteMilestone) }, reqRepoIssuesOrPullsWriter) @@ -1415,7 +1415,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // FIXME: many "pulls" requests are sent to "issues" endpoints incorrectly, need to move these routes to the proper place m.Group("/issues", func() { m.Post("/request_review", repo.UpdatePullReviewRequest) - m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview) + m.Post("/dismiss_review", reqRepoAdmin, web.Bind[*forms.DismissReviewForm](), repo.DismissReview) m.Post("/resolve_conversation", repo.SetShowOutdatedComments, repo.UpdateResolveConversation) }, reqUnitPullsReader) m.Post("/pull/{index}/target_branch", reqUnitPullsReader, repo.UpdatePullRequestTarget) @@ -1434,22 +1434,22 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { // the path params are used in PrepareCommitFormOptions to construct the correct form action URL m.Combo("/{editor_action:_edit}/*"). Get(repo.EditFile). - Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.EditFilePost) + Post(web.Bind[*forms.EditRepoFileForm](), canWriteToBranch, repo.EditFilePost) m.Combo("/{editor_action:_new}/*"). Get(repo.EditFile). - Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.EditFilePost) + Post(web.Bind[*forms.EditRepoFileForm](), canWriteToBranch, repo.EditFilePost) m.Combo("/{editor_action:_delete}/*"). Get(repo.DeleteFile). - Post(web.Bind(forms.DeleteRepoFileForm{}), canWriteToBranch, repo.DeleteFilePost) + Post(web.Bind[*forms.DeleteRepoFileForm](), canWriteToBranch, repo.DeleteFilePost) m.Combo("/{editor_action:_upload}/*", repo.MustBeAbleToUpload). Get(repo.UploadFile). - Post(web.Bind(forms.UploadRepoFileForm{}), canWriteToBranch, repo.UploadFilePost) + Post(web.Bind[*forms.UploadRepoFileForm](), canWriteToBranch, repo.UploadFilePost) m.Combo("/{editor_action:_diffpatch}/*"). Get(repo.NewDiffPatch). - Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.NewDiffPatchPost) + Post(web.Bind[*forms.EditRepoFileForm](), canWriteToBranch, repo.NewDiffPatchPost) m.Combo("/{editor_action:_cherrypick}/{sha:([a-f0-9]{7,64})}/*"). Get(repo.CherryPick). - Post(web.Bind(forms.CherryPickForm{}), canWriteToBranch, repo.CherryPickPost) + Post(web.Bind[*forms.CherryPickForm](), canWriteToBranch, repo.CherryPickPost) }, context.RepoRefByType(git.RefTypeBranch), repo.WebGitOperationCommonData) m.Group("", func() { m.Post("/upload-file", repo.UploadFileToServer) @@ -1462,14 +1462,14 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Post("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.CreateBranch) m.Post("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.CreateBranch) m.Post("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.CreateBranch) - }, web.Bind(forms.NewBranchForm{})) + }, web.Bind[*forms.NewBranchForm]()) m.Post("/delete", repo.DeleteBranchPost) m.Post("/restore", repo.RestoreBranchPost) - m.Post("/rename", web.Bind(forms.RenameBranchForm{}), repo_setting.RenameBranchPost) + m.Post("/rename", web.Bind[*forms.RenameBranchForm](), repo_setting.RenameBranchPost) m.Post("/merge-upstream", repo.MergeUpstream) }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty) - m.Combo("/fork").Get(repo.Fork).Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost) + m.Combo("/fork").Get(repo.Fork).Post(web.Bind[*forms.CreateRepoForm](), repo.ForkPost) }, reqSignIn, context.RepoAssignment, reqUnitCodeReader) // end "/{username}/{reponame}": repo code @@ -1496,10 +1496,10 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Get("/releases/download/{vTag}/{fileName}", webAuth.AllowBasic, webAuth.AllowOAuth2, repo.RedirectDownload) m.Group("/releases", func() { m.Get("/new", repo.NewRelease) - m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost) + m.Post("/new", web.Bind[*forms.NewReleaseForm](), repo.NewReleasePost) m.Get("/edit/*", repo.EditRelease) - m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost) - m.Post("/generate-notes", web.Bind(forms.GenerateReleaseNotesForm{}), repo.GenerateReleaseNotes) + m.Post("/edit/*", web.Bind[*forms.EditReleaseForm](), repo.EditReleasePost) + m.Post("/generate-notes", web.Bind[*forms.GenerateReleaseNotesForm](), repo.GenerateReleaseNotes) m.Post("/delete", repo.DeleteRelease) m.Post("/attachments", repo.UploadReleaseAttachment) m.Post("/attachments/remove", repo.DeleteAttachment) @@ -1527,12 +1527,12 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Get("/{id}", repo.ViewProject) m.Group("", func() { m.Get("/new", repo.RenderNewProject) - m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost) + m.Post("/new", web.Bind[*forms.CreateProjectForm](), repo.NewProjectPost) m.Group("/{id}", func() { m.Post("/delete", repo.DeleteProject) m.Get("/edit", repo.RenderEditProject) - m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost) + m.Post("/edit", web.Bind[*forms.CreateProjectForm](), repo.EditProjectPost) m.Post("/{action:open|close}", repo.ChangeProjectStatus) addProjectBoardRoutes(m) @@ -1552,16 +1552,16 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/runs/{run}", func() { m.Combo(""). Get(actions.View). - Post(web.Bind(actions.ViewRequest{}), actions.ViewPost) + Post(web.Bind[*actions.ViewRequest](), actions.ViewPost) m.Group("/attempts/{attempt}", func() { m.Combo(""). Get(actions.View). - Post(web.Bind(actions.ViewRequest{}), actions.ViewPost) + Post(web.Bind[*actions.ViewRequest](), actions.ViewPost) }) m.Group("/jobs/{job}", func() { m.Combo(""). Get(actions.View). - Post(web.Bind(actions.ViewRequest{}), actions.ViewPost) + Post(web.Bind[*actions.ViewRequest](), actions.ViewPost) m.Post("/rerun", reqRepoActionsWriter, actions.Rerun) m.Get("/logs", actions.Logs) }) @@ -1583,10 +1583,10 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Group("/{username}/{reponame}/wiki", func() { m.Combo(""). Get(repo.Wiki). - Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost) + Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind[*forms.NewWikiForm](), repo.WikiPost) m.Combo("/*"). Get(repo.Wiki). - Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost) + Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind[*forms.NewWikiForm](), repo.WikiPost) m.Get("/blob_excerpt/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob) m.Get("/commit/{sha:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff) m.Get("/commit/{sha:[a-f0-9]{7,64}}.{ext:patch|diff}", repo.RawDiff) @@ -1634,18 +1634,18 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Get("/list", repo.GetPullCommits) m.Get("/{sha:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForSingleCommit) }) - m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest) + m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind[*forms.MergePullRequestForm](), repo.MergePullRequest) m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest) m.Post("/update", repo.UpdatePullRequest) - m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits) + m.Post("/set_allow_maintainer_edit", web.Bind[*forms.UpdateAllowEditsForm](), repo.SetAllowEdits) m.Post("/cleanup", context.RepoMustNotBeArchived(), repo.CleanUpPullRequest) m.Group("/files", func() { m.Get("", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForAllCommitsOfPr) m.Get("/{shaFrom:[a-f0-9]{7,64}}..{shaTo:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForRange) m.Group("/reviews", func() { m.Get("/new_comment", repo.RenderNewCodeCommentForm) - m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.SetShowOutdatedComments, repo.CreateCodeComment) - m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview) + m.Post("/comments", web.Bind[*forms.CodeCommentForm](), repo.SetShowOutdatedComments, repo.CreateCodeComment) + m.Post("/submit", web.Bind[*forms.SubmitReviewForm](), repo.SubmitReview) }, context.RepoMustNotBeArchived()) }) }) @@ -1777,9 +1777,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) { m.Get("/repo-action-view/runs/{run}", devtest.MockActionsView) m.Get("/repo-action-view/runs/{run}/attempts/{attempt}", devtest.MockActionsView) m.Get("/repo-action-view/runs/{run}/jobs/{job}", devtest.MockActionsView) - m.Post("/repo-action-view/runs/{run}", web.Bind(actions.ViewRequest{}), devtest.MockActionsRunsJobs) - m.Post("/repo-action-view/runs/{run}/attempts/{attempt}", web.Bind(actions.ViewRequest{}), devtest.MockActionsRunsJobs) - m.Post("/repo-action-view/runs/{run}/jobs/{job}", web.Bind(actions.ViewRequest{}), devtest.MockActionsRunsJobs) + m.Post("/repo-action-view/runs/{run}", web.Bind[*actions.ViewRequest](), devtest.MockActionsRunsJobs) + m.Post("/repo-action-view/runs/{run}/attempts/{attempt}", web.Bind[*actions.ViewRequest](), devtest.MockActionsRunsJobs) + m.Post("/repo-action-view/runs/{run}/jobs/{job}", web.Bind[*actions.ViewRequest](), devtest.MockActionsRunsJobs) }) } diff --git a/services/context/context.go b/services/context/context.go index a240cb2b9e1..af42af390de 100644 --- a/services/context/context.go +++ b/services/context/context.go @@ -296,7 +296,6 @@ func GetFetchActionForm[T interface { if web.IsFormSet(ctx) { panic("don't mix fetch-action form validation with template-based form validation") } - middleware.SkipTmplFormValidationError(ctx) form := T(new(E)) errs := binding.Bind(ctx.Req, form) errorMessage, fieldName, _ := middleware.BuildValidationErrorForUser(form, ctx.Locale, errs) diff --git a/services/forms/admin.go b/services/forms/admin.go index 06c51c4146f..067cced6ef0 100644 --- a/services/forms/admin.go +++ b/services/forms/admin.go @@ -4,17 +4,13 @@ package forms import ( - "net/http" - "gitea.dev/modules/structs" "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" ) // AdminCreateUserForm form for admin to create user type AdminCreateUserForm struct { + middleware.FormDefaultValidator LoginType string `binding:"Required"` LoginName string UserName string `binding:"Required;Username;MaxSize(40)"` @@ -27,6 +23,7 @@ type AdminCreateUserForm struct { // AdminCreateBadgeForm form for admin to create badge type AdminCreateBadgeForm struct { + middleware.FormDefaultValidator Slug string `binding:"Required;BadgeSlug" locale:"admin.badges.slug"` Description string `binding:"Required" locale:"admin.badges.description"` ImageURL string `binding:"ValidUrl" locale:"admin.badges.image_url"` @@ -34,30 +31,14 @@ type AdminCreateBadgeForm struct { // AdminEditBadgeForm form for admin to edit badge type AdminEditBadgeForm struct { + middleware.FormDefaultValidator Description string `binding:"Required" locale:"admin.badges.description"` ImageURL string `binding:"ValidUrl" locale:"admin.badges.image_url"` } -// Validate validates form fields -func (f *AdminCreateBadgeForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - -// Validate validates form fields -func (f *AdminEditBadgeForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - -// Validate validates form fields -func (f *AdminCreateUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AdminEditUserForm form for admin to create user type AdminEditUserForm struct { + middleware.FormDefaultValidator LoginType string `binding:"Required"` UserName string `binding:"Username;MaxSize(40)"` LoginName string @@ -79,20 +60,9 @@ type AdminEditUserForm struct { Visibility structs.VisibleType } -// Validate validates form fields -func (f *AdminEditUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AdminDashboardForm form for admin dashboard operations type AdminDashboardForm struct { + middleware.FormDefaultValidator Op string `binding:"required"` From string } - -// Validate validates form fields -func (f *AdminDashboardForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/auth_form.go b/services/forms/auth_form.go index 92f9060bcfd..0875a0f81d2 100644 --- a/services/forms/auth_form.go +++ b/services/forms/auth_form.go @@ -3,17 +3,11 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" // AuthenticationForm form for authentication type AuthenticationForm struct { + middleware.FormDefaultValidator Type int `binding:"Range(2,7)"` Name string `binding:"Required;MaxSize(30)"` TwoFactorPolicy string @@ -96,9 +90,3 @@ type AuthenticationForm struct { SSPISeparatorReplacement string `binding:"AlphaDashDot;MaxSize(5)"` SSPIDefaultLanguage string } - -// Validate validates fields -func (f *AuthenticationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/org.go b/services/forms/org.go index 11f931ad140..57a9cbf10ca 100644 --- a/services/forms/org.go +++ b/services/forms/org.go @@ -5,13 +5,8 @@ package forms import ( - "net/http" - "gitea.dev/modules/structs" "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" ) // ________ .__ __ .__ @@ -23,19 +18,15 @@ import ( // CreateOrgForm form for creating organization type CreateOrgForm struct { + middleware.FormDefaultValidator OrgName string `binding:"Required;Username;MaxSize(40)" locale:"org.org_name_holder"` Visibility structs.VisibleType RepoAdminChangeTeamAccess bool } -// Validate validates the fields -func (f *CreateOrgForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // UpdateOrgSettingForm form for updating organization settings type UpdateOrgSettingForm struct { + middleware.FormDefaultValidator FullName *string `binding:"MaxSize(100)"` Email *string `binding:"MaxSize(255)"` Description *string `binding:"MaxSize(255)"` @@ -45,13 +36,8 @@ type UpdateOrgSettingForm struct { RepoAdminChangeTeamAccess *bool } -// Validate validates the fields -func (f *UpdateOrgSettingForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - type RenameOrgForm struct { + middleware.FormDefaultValidator OrgName string `binding:"Required"` NewOrgName string `binding:"Required;Username;MaxSize(40)" locale:"org.org_name_holder"` } @@ -65,6 +51,7 @@ type RenameOrgForm struct { // CreateTeamForm form for creating team type CreateTeamForm struct { + middleware.FormDefaultValidator TeamName string `binding:"Required;AlphaDashDot;MaxSize(255)"` Description string `binding:"MaxSize(255)"` Permission string @@ -72,9 +59,3 @@ type CreateTeamForm struct { CanCreateOrgRepo bool Visibility string `binding:"OmitEmpty;In(public,limited,private)"` } - -// Validate validates the fields -func (f *CreateTeamForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/package_form.go b/services/forms/package_form.go index 7bc946e50ef..017929de109 100644 --- a/services/forms/package_form.go +++ b/services/forms/package_form.go @@ -3,16 +3,10 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" type PackageCleanupRuleForm struct { + middleware.FormDefaultValidator ID int64 Enabled bool Type string `binding:"Required;In(alpine,arch,cargo,chef,composer,conan,conda,container,cran,debian,generic,go,helm,maven,npm,nuget,pub,pypi,rpm,rubygems,swift,terraform,vagrant)"` @@ -23,8 +17,3 @@ type PackageCleanupRuleForm struct { MatchFullName bool Action string `binding:"Required;In(save,remove)"` } - -func (f *PackageCleanupRuleForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/repo_branch_form.go b/services/forms/repo_branch_form.go index ce3586561be..c6b37b59b19 100644 --- a/services/forms/repo_branch_form.go +++ b/services/forms/repo_branch_form.go @@ -3,36 +3,19 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" // NewBranchForm form for creating a new branch type NewBranchForm struct { + middleware.FormDefaultValidator NewBranchName string `binding:"Required;MaxSize(100);GitRefName"` CurrentPath string CreateTag bool } -// Validate validates the fields -func (f *NewBranchForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // RenameBranchForm form for rename a branch type RenameBranchForm struct { + middleware.FormDefaultValidator From string `binding:"Required;MaxSize(100);GitRefName"` To string `binding:"Required;MaxSize(100);GitRefName"` } - -// Validate validates the fields -func (f *RenameBranchForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/repo_form.go b/services/forms/repo_form.go index a331193842b..bd28830e2a9 100644 --- a/services/forms/repo_form.go +++ b/services/forms/repo_form.go @@ -5,7 +5,6 @@ package forms import ( - "net/http" "strings" issues_model "gitea.dev/models/issues" @@ -14,7 +13,6 @@ import ( "gitea.dev/modules/structs" "gitea.dev/modules/util" "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" "gitea.dev/services/webhook" "gitea.com/go-chi/binding" @@ -22,6 +20,7 @@ import ( // CreateRepoForm form for creating repository type CreateRepoForm struct { + middleware.FormDefaultValidator UID int64 `binding:"Required"` RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Private bool @@ -47,15 +46,10 @@ type CreateRepoForm struct { ObjectFormatName string } -// Validate validates the fields -func (f *CreateRepoForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // MigrateRepoForm form for migrating repository // this is used to interact with web ui type MigrateRepoForm struct { + middleware.FormDefaultValidator // required: true CloneAddr string `json:"clone_addr" binding:"Required"` Service structs.GitServiceType `json:"service"` @@ -83,14 +77,9 @@ type MigrateRepoForm struct { AWSSecretAccessKey string `json:"aws_secret_access_key"` } -// Validate validates the fields -func (f *MigrateRepoForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // RepoSettingForm form for changing repository settings type RepoSettingForm struct { + middleware.FormDefaultValidator RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Description string `binding:"MaxSize(2048)"` Website string `binding:"ValidUrl;MaxSize(1024)"` @@ -160,14 +149,9 @@ type RepoSettingForm struct { RequestReindexType string } -// Validate validates the fields -func (f *RepoSettingForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ProtectBranchForm form for changing protected branch settings type ProtectBranchForm struct { + middleware.FormDefaultValidator RuleName string `binding:"Required"` RuleID int64 EnablePush string @@ -202,14 +186,9 @@ type ProtectBranchForm struct { BlockAdminMergeOverride bool } -// Validate validates the fields -func (f *ProtectBranchForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // WebhookForm form for changing web hook type WebhookForm struct { + middleware.FormDefaultValidator Name string `binding:"MaxSize(255)"` Events string Create bool @@ -259,31 +238,21 @@ func (f WebhookForm) ChooseEvents() bool { // NewWebhookForm form for creating web hook type NewWebhookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` HTTPMethod string `binding:"Required;In(POST,GET)"` ContentType int `binding:"Required"` WebhookForm } -// Validate validates the fields -func (f *NewWebhookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewGogshookForm form for creating gogs hook type NewGogshookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` ContentType int `binding:"Required"` WebhookForm } -// Validate validates the fields -func (f *NewGogshookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewSlackHookForm form for creating slack hook type NewSlackHookForm struct { PayloadURL string `binding:"Required;ValidUrl"` @@ -294,121 +263,80 @@ type NewSlackHookForm struct { WebhookForm } -// Validate validates the fields -func (f *NewSlackHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) +func (f *NewSlackHookForm) Validate(ctx *middleware.ValidateContext, errs binding.Errors) binding.Errors { if !webhook.IsValidSlackChannel(strings.TrimSpace(f.Channel)) { errs = middleware.AddValidationError(errs, "Channel", ctx.Locale.TrString("repo.settings.add_webhook.invalid_channel_name")) } - return middleware.Validate(ctx, errs, f) + return errs } // NewDiscordHookForm form for creating discord hook type NewDiscordHookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` Username string IconURL string WebhookForm } -// Validate validates the fields -func (f *NewDiscordHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewDingtalkHookForm form for creating dingtalk hook type NewDingtalkHookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` WebhookForm } -// Validate validates the fields -func (f *NewDingtalkHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewTelegramHookForm form for creating telegram hook type NewTelegramHookForm struct { + middleware.FormDefaultValidator BotToken string `binding:"Required"` ChatID string `binding:"Required"` ThreadID string WebhookForm } -// Validate validates the fields -func (f *NewTelegramHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewMatrixHookForm form for creating Matrix hook type NewMatrixHookForm struct { + middleware.FormDefaultValidator HomeserverURL string `binding:"Required;ValidUrl"` RoomID string `binding:"Required"` MessageType int WebhookForm } -// Validate validates the fields -func (f *NewMatrixHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewMSTeamsHookForm form for creating MS Teams hook type NewMSTeamsHookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` WebhookForm } -// Validate validates the fields -func (f *NewMSTeamsHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewFeishuHookForm form for creating feishu hook type NewFeishuHookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` WebhookForm } -// Validate validates the fields -func (f *NewFeishuHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewWechatWorkHookForm form for creating wechatwork hook type NewWechatWorkHookForm struct { + middleware.FormDefaultValidator PayloadURL string `binding:"Required;ValidUrl"` WebhookForm } -// Validate validates the fields -func (f *NewWechatWorkHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewPackagistHookForm form for creating packagist hook type NewPackagistHookForm struct { + middleware.FormDefaultValidator Username string `binding:"Required"` APIToken string `binding:"Required"` PackageURL string `binding:"Required;ValidUrl"` WebhookForm } -// Validate validates the fields -func (f *NewPackagistHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // CreateIssueForm form for creating issue type CreateIssueForm struct { + middleware.FormDefaultValidator Title string `binding:"Required;MaxSize(255)"` AssigneeIDs string `form:"assignee_ids"` ReviewerIDs string `form:"reviewer_ids"` @@ -419,49 +347,29 @@ type CreateIssueForm struct { AllowMaintainerEdit bool } -// Validate validates the fields -func (f *CreateIssueForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // CreateCommentForm form for creating comment type CreateCommentForm struct { + middleware.FormDefaultValidator Content string Status string `binding:"OmitEmpty;In(reopen,close)"` Files []string } -// Validate validates the fields -func (f *CreateCommentForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ReactionForm form for adding and removing reaction type ReactionForm struct { + middleware.FormDefaultValidator Content string `binding:"Required"` } -// Validate validates the fields -func (f *ReactionForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // IssueLockForm form for locking an issue type IssueLockForm struct { + middleware.FormDefaultValidator Reason string `binding:"Required"` } -// Validate validates the fields -func (f *IssueLockForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // CreateProjectForm form for creating a project type CreateProjectForm struct { + middleware.FormDefaultValidator Title string `binding:"Required;MaxSize(100)"` Content string TemplateType project_model.TemplateType @@ -470,6 +378,7 @@ type CreateProjectForm struct { // EditProjectColumnForm is a form for editing a project column type EditProjectColumnForm struct { + middleware.FormDefaultValidator Title string `binding:"Required;MaxSize(100)"` Sorting int8 Color string `binding:"MaxSize(7)"` @@ -477,19 +386,15 @@ type EditProjectColumnForm struct { // CreateMilestoneForm form for creating milestone type CreateMilestoneForm struct { + middleware.FormDefaultValidator Title string `binding:"Required;MaxSize(50)"` Content string Deadline string } -// Validate validates the fields -func (f *CreateMilestoneForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // CreateLabelForm form for creating label type CreateLabelForm struct { + middleware.FormDefaultValidator ID int64 Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_title"` Exclusive bool `form:"exclusive"` @@ -499,26 +404,16 @@ type CreateLabelForm struct { Color string `binding:"Required;MaxSize(7)" locale:"repo.issues.label_color"` } -// Validate validates the fields -func (f *CreateLabelForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // InitializeLabelsForm form for initializing labels type InitializeLabelsForm struct { + middleware.FormDefaultValidator TemplateName string `binding:"Required"` } -// Validate validates the fields -func (f *InitializeLabelsForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // MergePullRequestForm form for merging Pull Request // swagger:model MergePullRequestOption type MergePullRequestForm struct { + middleware.FormDefaultValidator // required: true // enum: ["merge","rebase","rebase-merge","squash","fast-forward-only","manually-merged"] Do string `json:"do" binding:"Required;In(merge,rebase,rebase-merge,squash,fast-forward-only,manually-merged)"` @@ -564,14 +459,9 @@ func (f *MergePullRequestForm) UnmarshalJSON(b []byte) error { return nil } -// Validate validates the fields -func (f *MergePullRequestForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // CodeCommentForm form for adding code comments for PRs type CodeCommentForm struct { + middleware.FormDefaultValidator Origin string `binding:"Required;In(timeline,diff)"` Content string `binding:"Required"` Side string `binding:"Required;In(previous,proposed)"` @@ -583,26 +473,15 @@ type CodeCommentForm struct { Files []string } -// Validate validates the fields -func (f *CodeCommentForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // SubmitReviewForm for submitting a finished code review type SubmitReviewForm struct { + middleware.FormDefaultValidator Content string Type string CommitID string Files []string } -// Validate validates the fields -func (f *SubmitReviewForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ReviewType will return the corresponding ReviewType for type func (f SubmitReviewForm) ReviewType() issues_model.ReviewType { switch f.Type { @@ -629,12 +508,14 @@ func (f SubmitReviewForm) HasEmptyContent() bool { // DismissReviewForm for dismissing stale review by repo admin type DismissReviewForm struct { + middleware.FormDefaultValidator ReviewID int64 `binding:"Required"` Message string } // UpdateAllowEditsForm form for changing if PR allows edits from maintainers type UpdateAllowEditsForm struct { + middleware.FormDefaultValidator AllowMaintainerEdit bool } @@ -647,6 +528,7 @@ type UpdateAllowEditsForm struct { // NewReleaseForm form for creating release type NewReleaseForm struct { + middleware.FormDefaultValidator TagName string `binding:"Required;GitRefName;MaxSize(255)"` Target string `form:"tag_target" binding:"Required;MaxSize(255)"` Title string `binding:"MaxSize(255)"` @@ -658,27 +540,17 @@ type NewReleaseForm struct { Files []string } -// Validate validates the fields -func (f *NewReleaseForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // GenerateReleaseNotesForm retrieves release notes recommendations. type GenerateReleaseNotesForm struct { + middleware.FormDefaultValidator TagName string `form:"tag_name" binding:"Required;GitRefName;MaxSize(255)"` TagTarget string `form:"tag_target" binding:"MaxSize(255)"` PreviousTag string `form:"previous_tag" binding:"MaxSize(255)"` } -// Validate validates the fields -func (f *GenerateReleaseNotesForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // EditReleaseForm form for changing release type EditReleaseForm struct { + middleware.FormDefaultValidator Title string `form:"title" binding:"Required;MaxSize(255)"` Content string `form:"content"` Draft string `form:"draft"` @@ -686,12 +558,6 @@ type EditReleaseForm struct { Files []string } -// Validate validates the fields -func (f *EditReleaseForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // __ __.__ __ .__ // / \ / \__| | _|__| // \ \/\/ / | |/ / | @@ -701,18 +567,12 @@ func (f *EditReleaseForm) Validate(req *http.Request, errs binding.Errors) bindi // NewWikiForm form for creating wiki type NewWikiForm struct { + middleware.FormDefaultValidator Title string `binding:"Required"` Content string `binding:"Required"` Message string } -// Validate validates the fields -// FIXME: use code generation to generate this method. -func (f *NewWikiForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ___________.__ ___________ __ // \__ ___/|__| _____ ____ \__ ___/___________ ____ | | __ ___________ // | | | |/ \_/ __ \ | | \_ __ \__ \ _/ ___\| |/ // __ \_ __ \ @@ -722,17 +582,13 @@ func (f *NewWikiForm) Validate(req *http.Request, errs binding.Errors) binding.E // AddTimeManuallyForm form that adds spent time manually. type AddTimeManuallyForm struct { + middleware.FormDefaultValidator Hours int `binding:"Range(0,1000)"` Minutes int `binding:"Range(0,1000)"` } -// Validate validates the fields -func (f *AddTimeManuallyForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // SaveTopicForm form for save topics for repository type SaveTopicForm struct { + middleware.FormDefaultValidator Topics []string `binding:"topics;Required;"` } diff --git a/services/forms/repo_form_editor.go b/services/forms/repo_form_editor.go index ff4687170e7..27e9292bec8 100644 --- a/services/forms/repo_form_editor.go +++ b/services/forms/repo_form_editor.go @@ -4,16 +4,12 @@ package forms import ( - "net/http" - "gitea.dev/modules/optional" "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" ) type CommitCommonForm struct { + middleware.FormDefaultValidator TreePath string `binding:"MaxSize(500)"` CommitSummary string `binding:"MaxSize(100)"` CommitMessage string @@ -24,11 +20,6 @@ type CommitCommonForm struct { CommitEmail string } -func (f *CommitCommonForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - type CommitCommonFormInterface interface { GetCommitCommonForm() *CommitCommonForm } @@ -38,20 +29,24 @@ func (f *CommitCommonForm) GetCommitCommonForm() *CommitCommonForm { } type EditRepoFileForm struct { + middleware.FormDefaultValidator CommitCommonForm Content optional.Option[string] } type DeleteRepoFileForm struct { + middleware.FormDefaultValidator CommitCommonForm } type UploadRepoFileForm struct { + middleware.FormDefaultValidator CommitCommonForm Files []string } type CherryPickForm struct { + middleware.FormDefaultValidator CommitCommonForm Revert bool } diff --git a/services/forms/repo_tag_form.go b/services/forms/repo_tag_form.go index 38a41d0c4c2..8624577fb51 100644 --- a/services/forms/repo_tag_form.go +++ b/services/forms/repo_tag_form.go @@ -3,24 +3,12 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" // ProtectTagForm form for changing protected tag settings type ProtectTagForm struct { + middleware.FormDefaultValidator NamePattern string `binding:"Required;GlobOrRegexPattern"` AllowlistUsers string AllowlistTeams string } - -// Validate validates the fields -func (f *ProtectTagForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/runner.go b/services/forms/runner.go index 573724f7a61..3025d852c64 100644 --- a/services/forms/runner.go +++ b/services/forms/runner.go @@ -3,22 +3,10 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" // EditRunnerForm form for admin to create runner type EditRunnerForm struct { + middleware.FormDefaultValidator Description string } - -// Validate validates form fields -func (f *EditRunnerForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/user_form.go b/services/forms/user_form.go index 012345fd5ee..bec7ba928b9 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -6,7 +6,6 @@ package forms import ( "mime/multipart" - "net/http" "strings" user_model "gitea.dev/models/user" @@ -15,13 +14,13 @@ import ( "gitea.dev/modules/util" "gitea.dev/modules/validation" "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" "gitea.com/go-chi/binding" ) // InstallForm form for installation page type InstallForm struct { + middleware.FormDefaultValidator DbType string `binding:"Required"` DbHost string DbUser string @@ -74,12 +73,6 @@ type InstallForm struct { ReinstallConfirmThird bool } -// Validate validates the fields -func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // _____ ____ _________________ ___ // / _ \ | | \__ ___/ | \ // / /_\ \| | / | | / ~ \ @@ -89,18 +82,13 @@ func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.E // RegisterForm form for registering type RegisterForm struct { + middleware.FormDefaultValidator UserName string `binding:"Required;Username;MaxSize(40)"` Email string `binding:"Required;MaxSize(254)"` Password string `binding:"MaxSize(255)"` Retype string } -// Validate validates the fields -func (f *RegisterForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // IsEmailDomainAllowed validates that the email address // provided by the user matches what has been configured . // The email is marked as allowed if it matches any of the @@ -113,34 +101,25 @@ func (f *RegisterForm) IsEmailDomainAllowed() bool { // MustChangePasswordForm form for updating your password after account creation // by an admin type MustChangePasswordForm struct { + middleware.FormDefaultValidator Password string `binding:"Required;MaxSize(255)"` Retype string } -// Validate validates the fields -func (f *MustChangePasswordForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // SignInForm form for signing in with user/password type SignInForm struct { + middleware.FormDefaultValidator UserName string `binding:"Required;MaxSize(254)"` // TODO remove required from password for SecondFactorAuthentication Password string `binding:"Required;MaxSize(255)"` Remember bool } -// Validate validates the fields -func (f *SignInForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AuthorizationForm form for authorizing oauth2 clients type AuthorizationForm struct { - ResponseType string `binding:"Required;In(code)"` - ClientID string `binding:"Required"` + middleware.FormDefaultValidator + ResponseType string + ClientID string RedirectURI string State string Scope string @@ -151,14 +130,9 @@ type AuthorizationForm struct { CodeChallenge string } -// Validate validates the fields -func (f *AuthorizationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // GrantApplicationForm form for authorizing oauth2 clients type GrantApplicationForm struct { + middleware.FormDefaultValidator ClientID string `binding:"Required"` Granted bool RedirectURI string @@ -167,14 +141,9 @@ type GrantApplicationForm struct { Nonce string } -// Validate validates the fields -func (f *GrantApplicationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AccessTokenForm for issuing access tokens from authorization codes or refresh tokens type AccessTokenForm struct { + middleware.FormDefaultValidator GrantType string `json:"grant_type"` ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"` @@ -186,23 +155,12 @@ type AccessTokenForm struct { CodeVerifier string `json:"code_verifier"` } -// Validate validates the fields -func (f *AccessTokenForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // IntrospectTokenForm for introspecting tokens type IntrospectTokenForm struct { + middleware.FormDefaultValidator Token string `json:"token"` } -// Validate validates the fields -func (f *IntrospectTokenForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // __________________________________________.___ _______ ________ _________ // / _____/\_ _____/\__ ___/\__ ___/| |\ \ / _____/ / _____/ // \_____ \ | __)_ | | | | | |/ | \/ \ ___ \_____ \ @@ -212,6 +170,7 @@ func (f *IntrospectTokenForm) Validate(req *http.Request, errs binding.Errors) b // UpdateProfileForm form for updating profile type UpdateProfileForm struct { + middleware.FormDefaultValidator Name string `binding:"Username;MaxSize(40)"` FullName string `binding:"MaxSize(100)"` KeepEmailPrivate bool @@ -222,86 +181,51 @@ type UpdateProfileForm struct { KeepActivityPrivate bool } -// Validate validates the fields -func (f *UpdateProfileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // UpdateLanguageForm form for updating profile type UpdateLanguageForm struct { + middleware.FormDefaultValidator Language string } -// Validate validates the fields -func (f *UpdateLanguageForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - const AvatarLocal = "local" // the AvatarForm.Source value that selects an uploaded avatar // AvatarForm form for changing avatar type AvatarForm struct { + middleware.FormDefaultValidator Source string Avatar *multipart.FileHeader Gravatar string `binding:"OmitEmpty;Email;MaxSize(254)"` } -// Validate validates the fields -func (f *AvatarForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AddEmailForm form for adding new email type AddEmailForm struct { + middleware.FormDefaultValidator Email string `binding:"Required;Email;MaxSize(254)"` } -// Validate validates the fields -func (f *AddEmailForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // UpdateThemeForm form for updating a users' theme type UpdateThemeForm struct { + middleware.FormDefaultValidator Theme string `binding:"Required;MaxSize(255)"` } -// Validate validates the field -func (f *UpdateThemeForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ChangePasswordForm form for changing password type ChangePasswordForm struct { + middleware.FormDefaultValidator OldPassword string `form:"old_password" binding:"MaxSize(255)"` Password string `form:"password" binding:"Required;MaxSize(255)"` Retype string `form:"retype"` } -// Validate validates the fields -func (f *ChangePasswordForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AddOpenIDForm is for changing openid uri type AddOpenIDForm struct { + middleware.FormDefaultValidator Openid string `binding:"Required;MaxSize(256)"` } -// Validate validates the fields -func (f *AddOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AddKeyForm form for adding SSH/GPG key type AddKeyForm struct { + middleware.FormDefaultValidator Type string `binding:"OmitEmpty"` Title string `binding:"Required;MaxSize(50)"` Content string `binding:"Required"` @@ -311,47 +235,27 @@ type AddKeyForm struct { IsWritable bool } -// Validate validates the fields -func (f *AddKeyForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // AddSecretForm for adding secrets type AddSecretForm struct { + middleware.FormDefaultValidator Name string `binding:"Required;MaxSize(255)"` Data string `binding:"Required;MaxSize(65535)"` Description string `binding:"MaxSize(65535)"` } -// Validate validates the fields -func (f *AddSecretForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - type EditVariableForm struct { + middleware.FormDefaultValidator Name string `binding:"Required;MaxSize(255)"` Data string `binding:"Required;MaxSize(65535)"` Description string `binding:"MaxSize(65535)"` } -func (f *EditVariableForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { + middleware.FormDefaultValidator Name string `binding:"Required;MaxSize(255)" locale:"settings.token_name"` } -// Validate validates the fields -func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // EditOAuth2ApplicationForm form for editing oauth2 applications type EditOAuth2ApplicationForm struct { Name string `binding:"Required;MaxSize(255)" form:"application_name"` @@ -371,68 +275,42 @@ func DetectInvalidOAuth2ApplicationRedirectURI(uris []string) (invalidURL string return "" } -// Validate validates the fields -func (f *EditOAuth2ApplicationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) +func (f *EditOAuth2ApplicationForm) Validate(ctx *middleware.ValidateContext, errs binding.Errors) binding.Errors { invalidURI := DetectInvalidOAuth2ApplicationRedirectURI(util.SplitTrimSpace(f.RedirectURIs, "\n")) if invalidURI != "" { errs = middleware.AddValidationError(errs, "RedirectURIs", "RedirectURIs: "+ctx.Locale.TrString("form.url_error", `"`+invalidURI+`"`)) } - return middleware.Validate(ctx, errs, f) + return errs } // TwoFactorAuthForm for logging in with 2FA token. type TwoFactorAuthForm struct { + middleware.FormDefaultValidator Passcode string `binding:"Required"` } -// Validate validates the fields -func (f *TwoFactorAuthForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // TwoFactorScratchAuthForm for logging in with 2FA scratch token. type TwoFactorScratchAuthForm struct { + middleware.FormDefaultValidator Token string `binding:"Required"` } -// Validate validates the fields -func (f *TwoFactorScratchAuthForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // WebauthnRegistrationForm for reserving an WebAuthn name type WebauthnRegistrationForm struct { + middleware.FormDefaultValidator Name string `binding:"Required"` } -// Validate validates the fields -func (f *WebauthnRegistrationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // PackageSettingForm form for package settings type PackageSettingForm struct { + middleware.FormDefaultValidator Action string RepoName string `form:"repo_name"` } -// Validate validates the fields -func (f *PackageSettingForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - type BlockUserForm struct { + middleware.FormDefaultValidator Action string `binding:"Required;In(block,unblock,note)"` Blockee string `binding:"Required"` Note string } - -func (f *BlockUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/services/forms/user_form_auth_openid.go b/services/forms/user_form_auth_openid.go index 9fee359c2f2..052473e53ac 100644 --- a/services/forms/user_form_auth_openid.go +++ b/services/forms/user_form_auth_openid.go @@ -3,47 +3,25 @@ package forms -import ( - "net/http" - - "gitea.dev/modules/web/middleware" - "gitea.dev/services/context" - - "gitea.com/go-chi/binding" -) +import "gitea.dev/modules/web/middleware" // SignInOpenIDForm form for signing in with OpenID type SignInOpenIDForm struct { + middleware.FormDefaultValidator Openid string `binding:"Required;MaxSize(256)"` Remember bool } -// Validate validates the fields -func (f *SignInOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // SignUpOpenIDForm form for signin up with OpenID type SignUpOpenIDForm struct { + middleware.FormDefaultValidator UserName string `binding:"Required;Username;MaxSize(40)"` Email string `binding:"Required;Email;MaxSize(254)"` } -// Validate validates the fields -func (f *SignUpOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} - // ConnectOpenIDForm form for connecting an existing account to an OpenID URI type ConnectOpenIDForm struct { + middleware.FormDefaultValidator UserName string `binding:"Required;MaxSize(254)"` Password string `binding:"Required;MaxSize(255)"` } - -// Validate validates the fields -func (f *ConnectOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetValidateContext(req) - return middleware.Validate(ctx, errs, f) -} diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go index be238a3bf7c..f9bc4907a3d 100644 --- a/tests/integration/auth_ldap_test.go +++ b/tests/integration/auth_ldap_test.go @@ -228,7 +228,7 @@ func testLDAPAuthChange(t *testing.T) { bindDN, _ := doc.Find(`input[name="bind_dn"]`).Attr("value") assert.Equal(t, "uid=gitea,ou=service,dc=planetexpress,dc=com", bindDN) - req = NewRequestWithValues(t, "POST", hrefAuthSource, te.buildAuthSourcePayload(map[string]string{"group_team_map_removal": "off"})) + req = NewRequestWithValues(t, "POST", hrefAuthSource, te.buildAuthSourcePayload(map[string]string{"group_team_map_removal": ""})) session.MakeRequest(t, req, http.StatusSeeOther) req = NewRequest(t, "GET", hrefAuthSource) @@ -492,7 +492,7 @@ func testLDAPPreventInvalidGroupTeamMap(t *testing.T) { te := prepareLdapTestServerEnv() session := loginUser(t, "user1") - payload := te.buildAuthSourcePayload(map[string]string{"group_team_map": `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, "group_team_map_removal": "off"}) + payload := te.buildAuthSourcePayload(map[string]string{"group_team_map": `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, "group_team_map_removal": ""}) req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload) session.MakeRequest(t, req, http.StatusOK) // StatusOK = failed, StatusSeeOther = ok } @@ -509,7 +509,6 @@ func testLDAPEmailSignin(t *testing.T) { }, }, serverHost: "mock-host", - serverPort: "mock-port", } defer test.MockVariableValue(&ldap.MockedSearchEntry, func(source *ldap.Source, name, passwd string, directBind bool) *ldap.SearchResult { var u *ldapUser