]> source.dussan.org Git - gitea.git/commitdiff
Move middlewares to web/middleware (#14480)
authorLunny Xiao <xiaolunwen@gmail.com>
Sat, 30 Jan 2021 08:55:53 +0000 (16:55 +0800)
committerGitHub <noreply@github.com>
Sat, 30 Jan 2021 08:55:53 +0000 (10:55 +0200)
Co-authored-by: 6543 <6543@obermui.de>
32 files changed:
modules/auth/sso/interface.go
modules/auth/sso/oauth2.go
modules/auth/sso/sso.go
modules/auth/sso/sspi_windows.go
modules/context/api.go
modules/context/context.go
modules/forms/admin.go
modules/forms/auth_form.go
modules/forms/org.go
modules/forms/repo_branch_form.go
modules/forms/repo_form.go
modules/forms/user_form.go
modules/forms/user_form_auth_openid.go
modules/middlewares/binding.go [deleted file]
modules/middlewares/cookie.go [deleted file]
modules/middlewares/data.go [deleted file]
modules/middlewares/flash.go [deleted file]
modules/middlewares/locale.go [deleted file]
modules/middlewares/request.go [deleted file]
modules/test/context_tests.go
modules/web/middleware/binding.go [new file with mode: 0644]
modules/web/middleware/cookie.go [new file with mode: 0644]
modules/web/middleware/data.go [new file with mode: 0644]
modules/web/middleware/flash.go [new file with mode: 0644]
modules/web/middleware/locale.go [new file with mode: 0644]
modules/web/middleware/request.go [new file with mode: 0644]
modules/web/route.go
routers/install.go
routers/repo/pull.go
routers/routes/base.go
routers/routes/install.go
routers/routes/web.go

index 7efe79a69c27d43c03eb8a71d59886dcbb823cfe..9b1472f2b37fb4363c5112f68e7c11a15579269a 100644 (file)
@@ -8,12 +8,12 @@ import (
        "net/http"
 
        "code.gitea.io/gitea/models"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/session"
+       "code.gitea.io/gitea/modules/web/middleware"
 )
 
 // DataStore represents a data store
-type DataStore middlewares.DataStore
+type DataStore middleware.DataStore
 
 // SessionStore represents a session store
 type SessionStore session.Store
index b6f59dc92420cccd5ae7391fbf54ce6622f3518f..fcd6845b38cc463a290f3331b1198d15e1fba7a8 100644 (file)
@@ -12,8 +12,8 @@ import (
 
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/timeutil"
+       "code.gitea.io/gitea/modules/web/middleware"
 )
 
 // Ensure the struct implements the interface.
@@ -122,7 +122,7 @@ func (o *OAuth2) VerifyAuthData(req *http.Request, w http.ResponseWriter, store
                return nil
        }
 
-       if middlewares.IsInternalPath(req) || !middlewares.IsAPIPath(req) && !isAttachmentDownload(req) {
+       if middleware.IsInternalPath(req) || !middleware.IsAPIPath(req) && !isAttachmentDownload(req) {
                return nil
        }
 
index f3788e4c9dd6795f0ed06c254dc56bdc63e93058..437bf3af7a938f68e492a2789094bb792b56ab37 100644 (file)
@@ -13,8 +13,8 @@ import (
 
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
+       "code.gitea.io/gitea/modules/web/middleware"
 )
 
 // ssoMethods contains the list of SSO authentication plugins in the order they are expected to be
@@ -121,7 +121,7 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
        // Language setting of the user overwrites the one previously set
        // If the user does not have a locale set, we save the current one.
        if len(user.Language) == 0 {
-               lc := middlewares.Locale(resp, req)
+               lc := middleware.Locale(resp, req)
                user.Language = lc.Language()
                if err := models.UpdateUserCols(user, "language"); err != nil {
                        log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", user.ID, user.Language))
@@ -129,8 +129,8 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
                }
        }
 
-       middlewares.SetCookie(resp, "lang", user.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
+       middleware.SetCookie(resp, "lang", user.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
 
        // Clear whatever CSRF has right now, force to generate a new one
-       middlewares.SetCookie(resp, setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
+       middleware.SetCookie(resp, setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
 }
index 10571d67c544f52c9c39c0717bd3f6ddfca99f57..46f7ad9d97a0a53c2703b20f76d805429b048abf 100644 (file)
@@ -12,9 +12,9 @@ import (
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/base"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/templates"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        gouuid "github.com/google/uuid"
        "github.com/quasoft/websspi"
@@ -136,7 +136,7 @@ func (s *SSPI) VerifyAuthData(req *http.Request, w http.ResponseWriter, store Da
        }
 
        // Make sure requests to API paths and PWA resources do not create a new session
-       if !middlewares.IsAPIPath(req) && !isAttachmentDownload(req) {
+       if !middleware.IsAPIPath(req) && !isAttachmentDownload(req) {
                handleSignIn(w, req, sess, user)
        }
 
@@ -167,9 +167,9 @@ func (s *SSPI) shouldAuthenticate(req *http.Request) (shouldAuth bool) {
                } else if req.FormValue("auth_with_sspi") == "1" {
                        shouldAuth = true
                }
-       } else if middlewares.IsInternalPath(req) {
+       } else if middleware.IsInternalPath(req) {
                shouldAuth = false
-       } else if middlewares.IsAPIPath(req) || isAttachmentDownload(req) {
+       } else if middleware.IsAPIPath(req) || isAttachmentDownload(req) {
                shouldAuth = true
        }
        return
index aab6905fd152c81867441c7ff90219c8efeb073b..4757c2eeb463f622236362513fe038c32d69b8d3 100644 (file)
@@ -17,8 +17,8 @@ import (
        "code.gitea.io/gitea/modules/auth/sso"
        "code.gitea.io/gitea/modules/git"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/session"
 )
@@ -224,7 +224,7 @@ func APIContexter() func(http.Handler) http.Handler {
        return func(next http.Handler) http.Handler {
 
                return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
-                       var locale = middlewares.Locale(w, req)
+                       var locale = middleware.Locale(w, req)
                        var ctx = APIContext{
                                Context: &Context{
                                        Resp:    NewResponse(w),
index 4fd0861df09653d6e64aa2c4d34046aed70082fa..bc48c1415de2d49217ead311d4e685137e6685e3 100644 (file)
@@ -26,11 +26,11 @@ import (
        "code.gitea.io/gitea/modules/base"
        mc "code.gitea.io/gitea/modules/cache"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/templates"
        "code.gitea.io/gitea/modules/translation"
        "code.gitea.io/gitea/modules/util"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/cache"
        "gitea.com/go-chi/session"
@@ -56,7 +56,7 @@ type Context struct {
        translation.Locale
        Cache   cache.Cache
        csrf    CSRF
-       Flash   *middlewares.Flash
+       Flash   *middleware.Flash
        Session session.Store
 
        Link        string // current request URL
@@ -206,7 +206,7 @@ func (ctx *Context) HTMLString(name string, data interface{}) (string, error) {
 // RenderWithErr used for page has form validation but need to prompt error to users.
 func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
        if form != nil {
-               middlewares.AssignForm(form, ctx.Data)
+               middleware.AssignForm(form, ctx.Data)
        }
        ctx.Flash.ErrorMsg = msg
        ctx.Data["Flash"] = ctx.Flash
@@ -384,12 +384,12 @@ func (ctx *Context) Redirect(location string, status ...int) {
 
 // SetCookie set cookies to web browser
 func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
-       middlewares.SetCookie(ctx.Resp, name, value, others...)
+       middleware.SetCookie(ctx.Resp, name, value, others...)
 }
 
 // GetCookie returns given cookie value from request header.
 func (ctx *Context) GetCookie(name string) string {
-       return middlewares.GetCookie(ctx.Req, name)
+       return middleware.GetCookie(ctx.Req, name)
 }
 
 // GetSuperSecureCookie returns given cookie value from request header with secret string.
@@ -496,10 +496,10 @@ func GetContext(req *http.Request) *Context {
 
 // SignedUserName returns signed user's name via context
 func SignedUserName(req *http.Request) string {
-       if middlewares.IsInternalPath(req) {
+       if middleware.IsInternalPath(req) {
                return ""
        }
-       if middlewares.IsAPIPath(req) {
+       if middleware.IsAPIPath(req) {
                ctx, ok := req.Context().Value(apiContextKey).(*APIContext)
                if ok {
                        v := ctx.Data["SignedUserName"]
@@ -539,7 +539,7 @@ func Contexter() func(next http.Handler) http.Handler {
 
        return func(next http.Handler) http.Handler {
                return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
-                       var locale = middlewares.Locale(resp, req)
+                       var locale = middleware.Locale(resp, req)
                        var startTime = time.Now()
                        var link = setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/")
                        var ctx = Context{
@@ -567,7 +567,7 @@ func Contexter() func(next http.Handler) http.Handler {
                        flashCookie := ctx.GetCookie("macaron_flash")
                        vals, _ := url.ParseQuery(flashCookie)
                        if len(vals) > 0 {
-                               f := &middlewares.Flash{
+                               f := &middleware.Flash{
                                        DataStore:  &ctx,
                                        Values:     vals,
                                        ErrorMsg:   vals.Get("error"),
@@ -578,7 +578,7 @@ func Contexter() func(next http.Handler) http.Handler {
                                ctx.Data["Flash"] = f
                        }
 
-                       f := &middlewares.Flash{
+                       f := &middleware.Flash{
                                DataStore:  &ctx,
                                Values:     url.Values{},
                                ErrorMsg:   "",
@@ -588,11 +588,11 @@ func Contexter() func(next http.Handler) http.Handler {
                        }
                        ctx.Resp.Before(func(resp ResponseWriter) {
                                if flash := f.Encode(); len(flash) > 0 {
-                                       middlewares.SetCookie(resp, "macaron_flash", flash, 0,
+                                       middleware.SetCookie(resp, "macaron_flash", flash, 0,
                                                setting.SessionConfig.CookiePath,
-                                               middlewares.Domain(setting.SessionConfig.Domain),
-                                               middlewares.HTTPOnly(true),
-                                               middlewares.Secure(setting.SessionConfig.Secure),
+                                               middleware.Domain(setting.SessionConfig.Domain),
+                                               middleware.HTTPOnly(true),
+                                               middleware.Secure(setting.SessionConfig.Secure),
                                                //middlewares.SameSite(opt.SameSite), FIXME: we need a samesite config
                                        )
                                        return
@@ -600,10 +600,10 @@ func Contexter() func(next http.Handler) http.Handler {
 
                                ctx.SetCookie("macaron_flash", "", -1,
                                        setting.SessionConfig.CookiePath,
-                                       middlewares.Domain(setting.SessionConfig.Domain),
-                                       middlewares.HTTPOnly(true),
-                                       middlewares.Secure(setting.SessionConfig.Secure),
-                                       //middlewares.SameSite(), FIXME: we need a samesite config
+                                       middleware.Domain(setting.SessionConfig.Domain),
+                                       middleware.HTTPOnly(true),
+                                       middleware.Secure(setting.SessionConfig.Secure),
+                                       //middleware.SameSite(), FIXME: we need a samesite config
                                )
                        })
 
index 09ad420e159ace367325a11dcef774ccc58b6c55..2e6bbaf172019439e57fdee3d6efffaa81739b7e 100644 (file)
@@ -8,7 +8,7 @@ import (
        "net/http"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
 )
@@ -27,7 +27,7 @@ type AdminCreateUserForm struct {
 // Validate validates form fields
 func (f *AdminCreateUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AdminEditUserForm form for admin to create user
@@ -54,7 +54,7 @@ type AdminEditUserForm struct {
 // Validate validates form fields
 func (f *AdminEditUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AdminDashboardForm form for admin dashboard operations
@@ -66,5 +66,5 @@ type AdminDashboardForm struct {
 // Validate validates form fields
 func (f *AdminDashboardForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index 10d0f829595373250105b7b074d66cbf16d4c041..7cf6b9fcd5edadb3ae5d86f207236b21cc8dadd5 100644 (file)
@@ -8,7 +8,7 @@ import (
        "net/http"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
 )
@@ -71,5 +71,5 @@ type AuthenticationForm struct {
 // Validate validates fields
 func (f *AuthenticationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index 513f80768fa99087a12a9cbdae0a5c3431fd0d0e..3b994770fd0ee097e65639508dcddb15e1462bdb 100644 (file)
@@ -10,8 +10,8 @@ import (
 
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/structs"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
 )
@@ -33,7 +33,7 @@ type CreateOrgForm struct {
 // Validate validates the fields
 func (f *CreateOrgForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // UpdateOrgSettingForm form for updating organization settings
@@ -51,7 +51,7 @@ type UpdateOrgSettingForm struct {
 // Validate validates the fields
 func (f *UpdateOrgSettingForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ___________
@@ -74,5 +74,5 @@ type CreateTeamForm struct {
 // Validate validates the fields
 func (f *CreateTeamForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index afb7f8d4f007bde6f388f04d4668c569758d5ab6..5c631f20d4b19751a17b39c9abf0dda958944517 100644 (file)
@@ -8,7 +8,7 @@ import (
        "net/http"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
 )
@@ -21,5 +21,5 @@ type NewBranchForm struct {
 // Validate validates the fields
 func (f *NewBranchForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index 4d37ab072b15ed45cedcfc92da557a5a67d39e67..ac968a1dd5b67ba2965980c5f907df95ab48e422 100644 (file)
@@ -13,10 +13,10 @@ import (
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/context"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/structs"
        "code.gitea.io/gitea/modules/util"
+       "code.gitea.io/gitea/modules/web/middleware"
        "code.gitea.io/gitea/routers/utils"
 
        "gitea.com/go-chi/binding"
@@ -56,7 +56,7 @@ type CreateRepoForm struct {
 // Validate validates the fields
 func (f *CreateRepoForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // MigrateRepoForm form for migrating repository
@@ -87,7 +87,7 @@ type MigrateRepoForm struct {
 // Validate validates the fields
 func (f *MigrateRepoForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ParseRemoteAddr checks if given remote address is valid,
@@ -172,7 +172,7 @@ type RepoSettingForm struct {
 // Validate validates the fields
 func (f *RepoSettingForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // __________                             .__
@@ -209,7 +209,7 @@ type ProtectBranchForm struct {
 // Validate validates the fields
 func (f *ProtectBranchForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 //  __      __      ___.   .__    .__            __
@@ -271,7 +271,7 @@ type NewWebhookForm struct {
 // Validate validates the fields
 func (f *NewWebhookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewGogshookForm form for creating gogs hook
@@ -285,7 +285,7 @@ type NewGogshookForm struct {
 // Validate validates the fields
 func (f *NewGogshookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewSlackHookForm form for creating slack hook
@@ -301,7 +301,7 @@ type NewSlackHookForm struct {
 // Validate validates the fields
 func (f *NewSlackHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // HasInvalidChannel validates the channel name is in the right format
@@ -320,7 +320,7 @@ type NewDiscordHookForm struct {
 // Validate validates the fields
 func (f *NewDiscordHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewDingtalkHookForm form for creating dingtalk hook
@@ -332,7 +332,7 @@ type NewDingtalkHookForm struct {
 // Validate validates the fields
 func (f *NewDingtalkHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewTelegramHookForm form for creating telegram hook
@@ -345,7 +345,7 @@ type NewTelegramHookForm struct {
 // Validate validates the fields
 func (f *NewTelegramHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewMatrixHookForm form for creating Matrix hook
@@ -360,7 +360,7 @@ type NewMatrixHookForm struct {
 // Validate validates the fields
 func (f *NewMatrixHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewMSTeamsHookForm form for creating MS Teams hook
@@ -372,7 +372,7 @@ type NewMSTeamsHookForm struct {
 // Validate validates the fields
 func (f *NewMSTeamsHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewFeishuHookForm form for creating feishu hook
@@ -384,7 +384,7 @@ type NewFeishuHookForm struct {
 // Validate validates the fields
 func (f *NewFeishuHookForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // .___
@@ -410,7 +410,7 @@ type CreateIssueForm struct {
 // Validate validates the fields
 func (f *CreateIssueForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // CreateCommentForm form for creating comment
@@ -423,7 +423,7 @@ type CreateCommentForm struct {
 // Validate validates the fields
 func (f *CreateCommentForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ReactionForm form for adding and removing reaction
@@ -434,7 +434,7 @@ type ReactionForm struct {
 // Validate validates the fields
 func (f *ReactionForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // IssueLockForm form for locking an issue
@@ -445,7 +445,7 @@ type IssueLockForm struct {
 // Validate validates the fields
 func (i *IssueLockForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, i, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, i, ctx.Locale)
 }
 
 // HasValidReason checks to make sure that the reason submitted in
@@ -510,7 +510,7 @@ type CreateMilestoneForm struct {
 // Validate validates the fields
 func (f *CreateMilestoneForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // .____          ___.          .__
@@ -531,7 +531,7 @@ type CreateLabelForm struct {
 // Validate validates the fields
 func (f *CreateLabelForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // InitializeLabelsForm form for initializing labels
@@ -542,7 +542,7 @@ type InitializeLabelsForm struct {
 // Validate validates the fields
 func (f *InitializeLabelsForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // __________      .__  .__    __________                                     __
@@ -566,7 +566,7 @@ type MergePullRequestForm struct {
 // Validate validates the fields
 func (f *MergePullRequestForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // CodeCommentForm form for adding code comments for PRs
@@ -584,7 +584,7 @@ type CodeCommentForm struct {
 // Validate validates the fields
 func (f *CodeCommentForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // SubmitReviewForm for submitting a finished code review
@@ -597,7 +597,7 @@ type SubmitReviewForm struct {
 // Validate validates the fields
 func (f *SubmitReviewForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ReviewType will return the corresponding reviewtype for type
@@ -643,7 +643,7 @@ type NewReleaseForm struct {
 // Validate validates the fields
 func (f *NewReleaseForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // EditReleaseForm form for changing release
@@ -658,7 +658,7 @@ type EditReleaseForm struct {
 // Validate validates the fields
 func (f *EditReleaseForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 //  __      __.__ __   .__
@@ -679,7 +679,7 @@ type NewWikiForm struct {
 // FIXME: use code generation to generate this method.
 func (f *NewWikiForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ___________    .___.__  __
@@ -704,7 +704,7 @@ type EditRepoFileForm struct {
 // Validate validates the fields
 func (f *EditRepoFileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // EditPreviewDiffForm form for changing preview diff
@@ -715,7 +715,7 @@ type EditPreviewDiffForm struct {
 // Validate validates the fields
 func (f *EditPreviewDiffForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 //  ____ ___        .__                    .___
@@ -740,7 +740,7 @@ type UploadRepoFileForm struct {
 // Validate validates the fields
 func (f *UploadRepoFileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // RemoveUploadFileForm form for removing uploaded file
@@ -751,7 +751,7 @@ type RemoveUploadFileForm struct {
 // Validate validates the fields
 func (f *RemoveUploadFileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ________         .__          __
@@ -774,7 +774,7 @@ type DeleteRepoFileForm struct {
 // Validate validates the fields
 func (f *DeleteRepoFileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ___________.__                 ___________                     __
@@ -793,7 +793,7 @@ type AddTimeManuallyForm struct {
 // Validate validates the fields
 func (f *AddTimeManuallyForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // SaveTopicForm form for save topics for repository
@@ -809,5 +809,5 @@ type DeadlineForm struct {
 // Validate validates the fields
 func (f *DeadlineForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index e3090f9ae5729ca1807dee42a19615b30df988ff..af36628c30fda4e85b0583e43a958e4ab07181f0 100644 (file)
@@ -11,8 +11,8 @@ import (
        "strings"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
 )
@@ -69,7 +69,7 @@ type InstallForm struct {
 // Validate validates the fields
 func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 //    _____   ____ _________________ ___
@@ -92,7 +92,7 @@ type RegisterForm struct {
 // Validate validates the fields
 func (f *RegisterForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // IsEmailDomainWhitelisted validates that the email address
@@ -130,7 +130,7 @@ type MustChangePasswordForm struct {
 // Validate validates the fields
 func (f *MustChangePasswordForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // SignInForm form for signing in with user/password
@@ -144,7 +144,7 @@ type SignInForm struct {
 // Validate validates the fields
 func (f *SignInForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AuthorizationForm form for authorizing oauth2 clients
@@ -164,7 +164,7 @@ type AuthorizationForm struct {
 // Validate validates the fields
 func (f *AuthorizationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // GrantApplicationForm form for authorizing oauth2 clients
@@ -179,7 +179,7 @@ type GrantApplicationForm struct {
 // Validate validates the fields
 func (f *GrantApplicationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AccessTokenForm for issuing access tokens from authorization codes or refresh tokens
@@ -198,7 +198,7 @@ type AccessTokenForm struct {
 // Validate validates the fields
 func (f *AccessTokenForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 //   __________________________________________.___ _______    ________  _________
@@ -223,7 +223,7 @@ type UpdateProfileForm struct {
 // Validate validates the fields
 func (f *UpdateProfileForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // Avatar types
@@ -243,7 +243,7 @@ type AvatarForm struct {
 // Validate validates the fields
 func (f *AvatarForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AddEmailForm form for adding new email
@@ -254,7 +254,7 @@ type AddEmailForm struct {
 // Validate validates the fields
 func (f *AddEmailForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // UpdateThemeForm form for updating a users' theme
@@ -265,7 +265,7 @@ type UpdateThemeForm struct {
 // Validate validates the field
 func (f *UpdateThemeForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // IsThemeExists checks if the theme is a theme available in the config.
@@ -292,7 +292,7 @@ type ChangePasswordForm struct {
 // Validate validates the fields
 func (f *ChangePasswordForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AddOpenIDForm is for changing openid uri
@@ -303,7 +303,7 @@ type AddOpenIDForm struct {
 // Validate validates the fields
 func (f *AddOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // AddKeyForm form for adding SSH/GPG key
@@ -317,7 +317,7 @@ type AddKeyForm struct {
 // Validate validates the fields
 func (f *AddKeyForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // NewAccessTokenForm form for creating access token
@@ -328,7 +328,7 @@ type NewAccessTokenForm struct {
 // Validate validates the fields
 func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // EditOAuth2ApplicationForm form for editing oauth2 applications
@@ -340,7 +340,7 @@ type EditOAuth2ApplicationForm struct {
 // Validate validates the fields
 func (f *EditOAuth2ApplicationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // TwoFactorAuthForm for logging in with 2FA token.
@@ -351,7 +351,7 @@ type TwoFactorAuthForm struct {
 // Validate validates the fields
 func (f *TwoFactorAuthForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // TwoFactorScratchAuthForm for logging in with 2FA scratch token.
@@ -362,7 +362,7 @@ type TwoFactorScratchAuthForm struct {
 // Validate validates the fields
 func (f *TwoFactorScratchAuthForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // U2FRegistrationForm for reserving an U2F name
@@ -373,7 +373,7 @@ type U2FRegistrationForm struct {
 // Validate validates the fields
 func (f *U2FRegistrationForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // U2FDeleteForm for deleting U2F keys
@@ -384,5 +384,5 @@ type U2FDeleteForm struct {
 // Validate validates the fields
 func (f *U2FDeleteForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
index 06601d7e15053313c2246be5b33044ac55d74860..b34f9dcc9724694f037927f0af29ce2f1e49e507 100644 (file)
@@ -8,7 +8,7 @@ import (
        "net/http"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
        "gitea.com/go-chi/binding"
 )
 
@@ -21,7 +21,7 @@ type SignInOpenIDForm struct {
 // Validate validates the fields
 func (f *SignInOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // SignUpOpenIDForm form for signin up with OpenID
@@ -35,7 +35,7 @@ type SignUpOpenIDForm struct {
 // Validate validates the fields
 func (f *SignUpOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
 
 // ConnectOpenIDForm form for connecting an existing account to an OpenID URI
@@ -47,5 +47,5 @@ type ConnectOpenIDForm struct {
 // Validate validates the fields
 func (f *ConnectOpenIDForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
        ctx := context.GetContext(req)
-       return middlewares.Validate(errs, ctx.Data, f, ctx.Locale)
+       return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
 }
diff --git a/modules/middlewares/binding.go b/modules/middlewares/binding.go
deleted file mode 100644 (file)
index 1dabdbb..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2014 The Gogs Authors. All rights reserved.
-// Copyright 2019 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-import (
-       "reflect"
-       "strings"
-
-       "code.gitea.io/gitea/modules/translation"
-       "code.gitea.io/gitea/modules/validation"
-
-       "gitea.com/go-chi/binding"
-       "github.com/unknwon/com"
-)
-
-// Form form binding interface
-type Form interface {
-       binding.Validator
-}
-
-func init() {
-       binding.SetNameMapper(com.ToSnakeCase)
-}
-
-// AssignForm assign form values back to the template data.
-func AssignForm(form interface{}, data map[string]interface{}) {
-       typ := reflect.TypeOf(form)
-       val := reflect.ValueOf(form)
-
-       for typ.Kind() == reflect.Ptr {
-               typ = typ.Elem()
-               val = val.Elem()
-       }
-
-       for i := 0; i < typ.NumField(); i++ {
-               field := typ.Field(i)
-
-               fieldName := field.Tag.Get("form")
-               // Allow ignored fields in the struct
-               if fieldName == "-" {
-                       continue
-               } else if len(fieldName) == 0 {
-                       fieldName = com.ToSnakeCase(field.Name)
-               }
-
-               data[fieldName] = val.Field(i).Interface()
-       }
-}
-
-func getRuleBody(field reflect.StructField, prefix string) string {
-       for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
-               if strings.HasPrefix(rule, prefix) {
-                       return rule[len(prefix) : len(rule)-1]
-               }
-       }
-       return ""
-}
-
-// GetSize get size int form tag
-func GetSize(field reflect.StructField) string {
-       return getRuleBody(field, "Size(")
-}
-
-// GetMinSize get minimal size in form tag
-func GetMinSize(field reflect.StructField) string {
-       return getRuleBody(field, "MinSize(")
-}
-
-// GetMaxSize get max size in form tag
-func GetMaxSize(field reflect.StructField) string {
-       return getRuleBody(field, "MaxSize(")
-}
-
-// GetInclude get include in form tag
-func GetInclude(field reflect.StructField) string {
-       return getRuleBody(field, "Include(")
-}
-
-// Validate validate TODO:
-func Validate(errs binding.Errors, data map[string]interface{}, f Form, l translation.Locale) binding.Errors {
-       if errs.Len() == 0 {
-               return errs
-       }
-
-       data["HasError"] = true
-       // If the field with name errs[0].FieldNames[0] is not found in form
-       // somehow, some code later on will panic on Data["ErrorMsg"].(string).
-       // So initialize it to some default.
-       data["ErrorMsg"] = l.Tr("form.unknown_error")
-       AssignForm(f, data)
-
-       typ := reflect.TypeOf(f)
-       val := reflect.ValueOf(f)
-
-       if typ.Kind() == reflect.Ptr {
-               typ = typ.Elem()
-               val = val.Elem()
-       }
-
-       if field, ok := typ.FieldByName(errs[0].FieldNames[0]); ok {
-               fieldName := field.Tag.Get("form")
-               if fieldName != "-" {
-                       data["Err_"+field.Name] = true
-
-                       trName := field.Tag.Get("locale")
-                       if len(trName) == 0 {
-                               trName = l.Tr("form." + field.Name)
-                       } else {
-                               trName = l.Tr(trName)
-                       }
-
-                       switch errs[0].Classification {
-                       case binding.ERR_REQUIRED:
-                               data["ErrorMsg"] = trName + l.Tr("form.require_error")
-                       case binding.ERR_ALPHA_DASH:
-                               data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
-                       case binding.ERR_ALPHA_DASH_DOT:
-                               data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
-                       case validation.ErrGitRefName:
-                               data["ErrorMsg"] = trName + l.Tr("form.git_ref_name_error")
-                       case binding.ERR_SIZE:
-                               data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field))
-                       case binding.ERR_MIN_SIZE:
-                               data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
-                       case binding.ERR_MAX_SIZE:
-                               data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
-                       case binding.ERR_EMAIL:
-                               data["ErrorMsg"] = trName + l.Tr("form.email_error")
-                       case binding.ERR_URL:
-                               data["ErrorMsg"] = trName + l.Tr("form.url_error")
-                       case binding.ERR_INCLUDE:
-                               data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field))
-                       case validation.ErrGlobPattern:
-                               data["ErrorMsg"] = trName + l.Tr("form.glob_pattern_error", errs[0].Message)
-                       default:
-                               data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
-                       }
-                       return errs
-               }
-       }
-       return errs
-}
diff --git a/modules/middlewares/cookie.go b/modules/middlewares/cookie.go
deleted file mode 100644 (file)
index d185418..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2020 The Macaron Authors
-// Copyright 2020 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-import (
-       "net/http"
-       "net/url"
-       "time"
-
-       "code.gitea.io/gitea/modules/setting"
-)
-
-// MaxAge sets the maximum age for a provided cookie
-func MaxAge(maxAge int) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.MaxAge = maxAge
-       }
-}
-
-// Path sets the path for a provided cookie
-func Path(path string) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.Path = path
-       }
-}
-
-// Domain sets the domain for a provided cookie
-func Domain(domain string) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.Domain = domain
-       }
-}
-
-// Secure sets the secure setting for a provided cookie
-func Secure(secure bool) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.Secure = secure
-       }
-}
-
-// HTTPOnly sets the HttpOnly setting for a provided cookie
-func HTTPOnly(httpOnly bool) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.HttpOnly = httpOnly
-       }
-}
-
-// Expires sets the expires and rawexpires for a provided cookie
-func Expires(expires time.Time) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.Expires = expires
-               c.RawExpires = expires.Format(time.UnixDate)
-       }
-}
-
-// SameSite sets the SameSite for a provided cookie
-func SameSite(sameSite http.SameSite) func(*http.Cookie) {
-       return func(c *http.Cookie) {
-               c.SameSite = sameSite
-       }
-}
-
-// NewCookie creates a cookie
-func NewCookie(name, value string, maxAge int) *http.Cookie {
-       return &http.Cookie{
-               Name:     name,
-               Value:    value,
-               HttpOnly: true,
-               Path:     setting.SessionConfig.CookiePath,
-               Domain:   setting.SessionConfig.Domain,
-               MaxAge:   maxAge,
-               Secure:   setting.SessionConfig.Secure,
-       }
-}
-
-// SetCookie set the cookies
-// TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed.
-func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) {
-       cookie := http.Cookie{}
-       cookie.Name = name
-       cookie.Value = url.QueryEscape(value)
-
-       if len(others) > 0 {
-               switch v := others[0].(type) {
-               case int:
-                       cookie.MaxAge = v
-               case int64:
-                       cookie.MaxAge = int(v)
-               case int32:
-                       cookie.MaxAge = int(v)
-               case func(*http.Cookie):
-                       v(&cookie)
-               }
-       }
-
-       cookie.Path = "/"
-       if len(others) > 1 {
-               if v, ok := others[1].(string); ok && len(v) > 0 {
-                       cookie.Path = v
-               } else if v, ok := others[1].(func(*http.Cookie)); ok {
-                       v(&cookie)
-               }
-       }
-
-       if len(others) > 2 {
-               if v, ok := others[2].(string); ok && len(v) > 0 {
-                       cookie.Domain = v
-               } else if v, ok := others[1].(func(*http.Cookie)); ok {
-                       v(&cookie)
-               }
-       }
-
-       if len(others) > 3 {
-               switch v := others[3].(type) {
-               case bool:
-                       cookie.Secure = v
-               case func(*http.Cookie):
-                       v(&cookie)
-               default:
-                       if others[3] != nil {
-                               cookie.Secure = true
-                       }
-               }
-       }
-
-       if len(others) > 4 {
-               if v, ok := others[4].(bool); ok && v {
-                       cookie.HttpOnly = true
-               } else if v, ok := others[1].(func(*http.Cookie)); ok {
-                       v(&cookie)
-               }
-       }
-
-       if len(others) > 5 {
-               if v, ok := others[5].(time.Time); ok {
-                       cookie.Expires = v
-                       cookie.RawExpires = v.Format(time.UnixDate)
-               } else if v, ok := others[1].(func(*http.Cookie)); ok {
-                       v(&cookie)
-               }
-       }
-
-       if len(others) > 6 {
-               for _, other := range others[6:] {
-                       if v, ok := other.(func(*http.Cookie)); ok {
-                               v(&cookie)
-                       }
-               }
-       }
-
-       resp.Header().Add("Set-Cookie", cookie.String())
-}
-
-// GetCookie returns given cookie value from request header.
-func GetCookie(req *http.Request, name string) string {
-       cookie, err := req.Cookie(name)
-       if err != nil {
-               return ""
-       }
-       val, _ := url.QueryUnescape(cookie.Value)
-       return val
-}
diff --git a/modules/middlewares/data.go b/modules/middlewares/data.go
deleted file mode 100644 (file)
index 2690289..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-// Copyright 2020 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-// DataStore represents a data store
-type DataStore interface {
-       GetData() map[string]interface{}
-}
diff --git a/modules/middlewares/flash.go b/modules/middlewares/flash.go
deleted file mode 100644 (file)
index 732e1c7..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2020 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-import "net/url"
-
-// flashes enumerates all the flash types
-const (
-       SuccessFlash = "SuccessMsg"
-       ErrorFlash   = "ErrorMsg"
-       WarnFlash    = "WarningMsg"
-       InfoFlash    = "InfoMsg"
-)
-
-var (
-       // FlashNow FIXME:
-       FlashNow bool
-)
-
-// Flash represents a one time data transfer between two requests.
-type Flash struct {
-       DataStore
-       url.Values
-       ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
-}
-
-func (f *Flash) set(name, msg string, current ...bool) {
-       if f.Values == nil {
-               f.Values = make(map[string][]string)
-       }
-       isShow := false
-       if (len(current) == 0 && FlashNow) ||
-               (len(current) > 0 && current[0]) {
-               isShow = true
-       }
-
-       if isShow {
-               f.GetData()["Flash"] = f
-       } else {
-               f.Set(name, msg)
-       }
-}
-
-// Error sets error message
-func (f *Flash) Error(msg string, current ...bool) {
-       f.ErrorMsg = msg
-       f.set("error", msg, current...)
-}
-
-// Warning sets warning message
-func (f *Flash) Warning(msg string, current ...bool) {
-       f.WarningMsg = msg
-       f.set("warning", msg, current...)
-}
-
-// Info sets info message
-func (f *Flash) Info(msg string, current ...bool) {
-       f.InfoMsg = msg
-       f.set("info", msg, current...)
-}
-
-// Success sets success message
-func (f *Flash) Success(msg string, current ...bool) {
-       f.SuccessMsg = msg
-       f.set("success", msg, current...)
-}
diff --git a/modules/middlewares/locale.go b/modules/middlewares/locale.go
deleted file mode 100644 (file)
index 21980ad..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-import (
-       "net/http"
-
-       "code.gitea.io/gitea/modules/translation"
-
-       "github.com/unknwon/i18n"
-       "golang.org/x/text/language"
-)
-
-// Locale handle locale
-func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
-       // 1. Check URL arguments.
-       lang := req.URL.Query().Get("lang")
-       var changeLang = lang != ""
-
-       // 2. Get language information from cookies.
-       if len(lang) == 0 {
-               ck, _ := req.Cookie("lang")
-               if ck != nil {
-                       lang = ck.Value
-               }
-       }
-
-       // Check again in case someone modify by purpose.
-       if lang != "" && !i18n.IsExist(lang) {
-               lang = ""
-               changeLang = false
-       }
-
-       // 3. Get language information from 'Accept-Language'.
-       // The first element in the list is chosen to be the default language automatically.
-       if len(lang) == 0 {
-               tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
-               tag, _, _ := translation.Match(tags...)
-               lang = tag.String()
-       }
-
-       if changeLang {
-               SetCookie(resp, "lang", lang, 1<<31-1)
-       }
-
-       return translation.NewLocale(lang)
-}
diff --git a/modules/middlewares/request.go b/modules/middlewares/request.go
deleted file mode 100644 (file)
index aa3d60b..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2020 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middlewares
-
-import (
-       "net/http"
-       "strings"
-)
-
-// IsAPIPath returns true if the specified URL is an API path
-func IsAPIPath(req *http.Request) bool {
-       return strings.HasPrefix(req.URL.Path, "/api/")
-}
-
-// IsInternalPath returns true if the specified URL is an internal API path
-func IsInternalPath(req *http.Request) bool {
-       return strings.HasPrefix(req.URL.Path, "/api/internal/")
-}
index e219a8e56ab0a458bfd8d56e671c44bfe1655f77..a15c74d82800b5486c6a5eab4d676e66afe9dd15 100644 (file)
@@ -16,7 +16,7 @@ import (
        "code.gitea.io/gitea/models"
        "code.gitea.io/gitea/modules/context"
        "code.gitea.io/gitea/modules/git"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "github.com/go-chi/chi"
        "github.com/stretchr/testify/assert"
@@ -29,7 +29,7 @@ func MockContext(t *testing.T, path string) *context.Context {
        var ctx = context.Context{
                Render: &mockRender{},
                Data:   make(map[string]interface{}),
-               Flash: &middlewares.Flash{
+               Flash: &middleware.Flash{
                        Values: make(url.Values),
                },
                Resp:   context.NewResponse(resp),
diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go
new file mode 100644 (file)
index 0000000..cd418c9
--- /dev/null
@@ -0,0 +1,145 @@
+// Copyright 2014 The Gogs Authors. All rights reserved.
+// Copyright 2019 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+       "reflect"
+       "strings"
+
+       "code.gitea.io/gitea/modules/translation"
+       "code.gitea.io/gitea/modules/validation"
+
+       "gitea.com/go-chi/binding"
+       "github.com/unknwon/com"
+)
+
+// Form form binding interface
+type Form interface {
+       binding.Validator
+}
+
+func init() {
+       binding.SetNameMapper(com.ToSnakeCase)
+}
+
+// AssignForm assign form values back to the template data.
+func AssignForm(form interface{}, data map[string]interface{}) {
+       typ := reflect.TypeOf(form)
+       val := reflect.ValueOf(form)
+
+       for typ.Kind() == reflect.Ptr {
+               typ = typ.Elem()
+               val = val.Elem()
+       }
+
+       for i := 0; i < typ.NumField(); i++ {
+               field := typ.Field(i)
+
+               fieldName := field.Tag.Get("form")
+               // Allow ignored fields in the struct
+               if fieldName == "-" {
+                       continue
+               } else if len(fieldName) == 0 {
+                       fieldName = com.ToSnakeCase(field.Name)
+               }
+
+               data[fieldName] = val.Field(i).Interface()
+       }
+}
+
+func getRuleBody(field reflect.StructField, prefix string) string {
+       for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
+               if strings.HasPrefix(rule, prefix) {
+                       return rule[len(prefix) : len(rule)-1]
+               }
+       }
+       return ""
+}
+
+// GetSize get size int form tag
+func GetSize(field reflect.StructField) string {
+       return getRuleBody(field, "Size(")
+}
+
+// GetMinSize get minimal size in form tag
+func GetMinSize(field reflect.StructField) string {
+       return getRuleBody(field, "MinSize(")
+}
+
+// GetMaxSize get max size in form tag
+func GetMaxSize(field reflect.StructField) string {
+       return getRuleBody(field, "MaxSize(")
+}
+
+// GetInclude get include in form tag
+func GetInclude(field reflect.StructField) string {
+       return getRuleBody(field, "Include(")
+}
+
+// Validate validate TODO:
+func Validate(errs binding.Errors, data map[string]interface{}, f Form, l translation.Locale) binding.Errors {
+       if errs.Len() == 0 {
+               return errs
+       }
+
+       data["HasError"] = true
+       // If the field with name errs[0].FieldNames[0] is not found in form
+       // somehow, some code later on will panic on Data["ErrorMsg"].(string).
+       // So initialize it to some default.
+       data["ErrorMsg"] = l.Tr("form.unknown_error")
+       AssignForm(f, data)
+
+       typ := reflect.TypeOf(f)
+       val := reflect.ValueOf(f)
+
+       if typ.Kind() == reflect.Ptr {
+               typ = typ.Elem()
+               val = val.Elem()
+       }
+
+       if field, ok := typ.FieldByName(errs[0].FieldNames[0]); ok {
+               fieldName := field.Tag.Get("form")
+               if fieldName != "-" {
+                       data["Err_"+field.Name] = true
+
+                       trName := field.Tag.Get("locale")
+                       if len(trName) == 0 {
+                               trName = l.Tr("form." + field.Name)
+                       } else {
+                               trName = l.Tr(trName)
+                       }
+
+                       switch errs[0].Classification {
+                       case binding.ERR_REQUIRED:
+                               data["ErrorMsg"] = trName + l.Tr("form.require_error")
+                       case binding.ERR_ALPHA_DASH:
+                               data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
+                       case binding.ERR_ALPHA_DASH_DOT:
+                               data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
+                       case validation.ErrGitRefName:
+                               data["ErrorMsg"] = trName + l.Tr("form.git_ref_name_error")
+                       case binding.ERR_SIZE:
+                               data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field))
+                       case binding.ERR_MIN_SIZE:
+                               data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
+                       case binding.ERR_MAX_SIZE:
+                               data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
+                       case binding.ERR_EMAIL:
+                               data["ErrorMsg"] = trName + l.Tr("form.email_error")
+                       case binding.ERR_URL:
+                               data["ErrorMsg"] = trName + l.Tr("form.url_error")
+                       case binding.ERR_INCLUDE:
+                               data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field))
+                       case validation.ErrGlobPattern:
+                               data["ErrorMsg"] = trName + l.Tr("form.glob_pattern_error", errs[0].Message)
+                       default:
+                               data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
+                       }
+                       return errs
+               }
+       }
+       return errs
+}
diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go
new file mode 100644 (file)
index 0000000..83e365f
--- /dev/null
@@ -0,0 +1,165 @@
+// Copyright 2020 The Macaron Authors
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+       "net/http"
+       "net/url"
+       "time"
+
+       "code.gitea.io/gitea/modules/setting"
+)
+
+// MaxAge sets the maximum age for a provided cookie
+func MaxAge(maxAge int) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.MaxAge = maxAge
+       }
+}
+
+// Path sets the path for a provided cookie
+func Path(path string) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.Path = path
+       }
+}
+
+// Domain sets the domain for a provided cookie
+func Domain(domain string) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.Domain = domain
+       }
+}
+
+// Secure sets the secure setting for a provided cookie
+func Secure(secure bool) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.Secure = secure
+       }
+}
+
+// HTTPOnly sets the HttpOnly setting for a provided cookie
+func HTTPOnly(httpOnly bool) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.HttpOnly = httpOnly
+       }
+}
+
+// Expires sets the expires and rawexpires for a provided cookie
+func Expires(expires time.Time) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.Expires = expires
+               c.RawExpires = expires.Format(time.UnixDate)
+       }
+}
+
+// SameSite sets the SameSite for a provided cookie
+func SameSite(sameSite http.SameSite) func(*http.Cookie) {
+       return func(c *http.Cookie) {
+               c.SameSite = sameSite
+       }
+}
+
+// NewCookie creates a cookie
+func NewCookie(name, value string, maxAge int) *http.Cookie {
+       return &http.Cookie{
+               Name:     name,
+               Value:    value,
+               HttpOnly: true,
+               Path:     setting.SessionConfig.CookiePath,
+               Domain:   setting.SessionConfig.Domain,
+               MaxAge:   maxAge,
+               Secure:   setting.SessionConfig.Secure,
+       }
+}
+
+// SetCookie set the cookies
+// TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed.
+func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) {
+       cookie := http.Cookie{}
+       cookie.Name = name
+       cookie.Value = url.QueryEscape(value)
+
+       if len(others) > 0 {
+               switch v := others[0].(type) {
+               case int:
+                       cookie.MaxAge = v
+               case int64:
+                       cookie.MaxAge = int(v)
+               case int32:
+                       cookie.MaxAge = int(v)
+               case func(*http.Cookie):
+                       v(&cookie)
+               }
+       }
+
+       cookie.Path = "/"
+       if len(others) > 1 {
+               if v, ok := others[1].(string); ok && len(v) > 0 {
+                       cookie.Path = v
+               } else if v, ok := others[1].(func(*http.Cookie)); ok {
+                       v(&cookie)
+               }
+       }
+
+       if len(others) > 2 {
+               if v, ok := others[2].(string); ok && len(v) > 0 {
+                       cookie.Domain = v
+               } else if v, ok := others[1].(func(*http.Cookie)); ok {
+                       v(&cookie)
+               }
+       }
+
+       if len(others) > 3 {
+               switch v := others[3].(type) {
+               case bool:
+                       cookie.Secure = v
+               case func(*http.Cookie):
+                       v(&cookie)
+               default:
+                       if others[3] != nil {
+                               cookie.Secure = true
+                       }
+               }
+       }
+
+       if len(others) > 4 {
+               if v, ok := others[4].(bool); ok && v {
+                       cookie.HttpOnly = true
+               } else if v, ok := others[1].(func(*http.Cookie)); ok {
+                       v(&cookie)
+               }
+       }
+
+       if len(others) > 5 {
+               if v, ok := others[5].(time.Time); ok {
+                       cookie.Expires = v
+                       cookie.RawExpires = v.Format(time.UnixDate)
+               } else if v, ok := others[1].(func(*http.Cookie)); ok {
+                       v(&cookie)
+               }
+       }
+
+       if len(others) > 6 {
+               for _, other := range others[6:] {
+                       if v, ok := other.(func(*http.Cookie)); ok {
+                               v(&cookie)
+                       }
+               }
+       }
+
+       resp.Header().Add("Set-Cookie", cookie.String())
+}
+
+// GetCookie returns given cookie value from request header.
+func GetCookie(req *http.Request, name string) string {
+       cookie, err := req.Cookie(name)
+       if err != nil {
+               return ""
+       }
+       val, _ := url.QueryUnescape(cookie.Value)
+       return val
+}
diff --git a/modules/web/middleware/data.go b/modules/web/middleware/data.go
new file mode 100644 (file)
index 0000000..7de6864
--- /dev/null
@@ -0,0 +1,10 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+// DataStore represents a data store
+type DataStore interface {
+       GetData() map[string]interface{}
+}
diff --git a/modules/web/middleware/flash.go b/modules/web/middleware/flash.go
new file mode 100644 (file)
index 0000000..cd9b089
--- /dev/null
@@ -0,0 +1,68 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import "net/url"
+
+// flashes enumerates all the flash types
+const (
+       SuccessFlash = "SuccessMsg"
+       ErrorFlash   = "ErrorMsg"
+       WarnFlash    = "WarningMsg"
+       InfoFlash    = "InfoMsg"
+)
+
+var (
+       // FlashNow FIXME:
+       FlashNow bool
+)
+
+// Flash represents a one time data transfer between two requests.
+type Flash struct {
+       DataStore
+       url.Values
+       ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
+}
+
+func (f *Flash) set(name, msg string, current ...bool) {
+       if f.Values == nil {
+               f.Values = make(map[string][]string)
+       }
+       isShow := false
+       if (len(current) == 0 && FlashNow) ||
+               (len(current) > 0 && current[0]) {
+               isShow = true
+       }
+
+       if isShow {
+               f.GetData()["Flash"] = f
+       } else {
+               f.Set(name, msg)
+       }
+}
+
+// Error sets error message
+func (f *Flash) Error(msg string, current ...bool) {
+       f.ErrorMsg = msg
+       f.set("error", msg, current...)
+}
+
+// Warning sets warning message
+func (f *Flash) Warning(msg string, current ...bool) {
+       f.WarningMsg = msg
+       f.set("warning", msg, current...)
+}
+
+// Info sets info message
+func (f *Flash) Info(msg string, current ...bool) {
+       f.InfoMsg = msg
+       f.set("info", msg, current...)
+}
+
+// Success sets success message
+func (f *Flash) Success(msg string, current ...bool) {
+       f.SuccessMsg = msg
+       f.set("success", msg, current...)
+}
diff --git a/modules/web/middleware/locale.go b/modules/web/middleware/locale.go
new file mode 100644 (file)
index 0000000..449095f
--- /dev/null
@@ -0,0 +1,49 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+       "net/http"
+
+       "code.gitea.io/gitea/modules/translation"
+
+       "github.com/unknwon/i18n"
+       "golang.org/x/text/language"
+)
+
+// Locale handle locale
+func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
+       // 1. Check URL arguments.
+       lang := req.URL.Query().Get("lang")
+       var changeLang = lang != ""
+
+       // 2. Get language information from cookies.
+       if len(lang) == 0 {
+               ck, _ := req.Cookie("lang")
+               if ck != nil {
+                       lang = ck.Value
+               }
+       }
+
+       // Check again in case someone modify by purpose.
+       if lang != "" && !i18n.IsExist(lang) {
+               lang = ""
+               changeLang = false
+       }
+
+       // 3. Get language information from 'Accept-Language'.
+       // The first element in the list is chosen to be the default language automatically.
+       if len(lang) == 0 {
+               tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
+               tag, _, _ := translation.Match(tags...)
+               lang = tag.String()
+       }
+
+       if changeLang {
+               SetCookie(resp, "lang", lang, 1<<31-1)
+       }
+
+       return translation.NewLocale(lang)
+}
diff --git a/modules/web/middleware/request.go b/modules/web/middleware/request.go
new file mode 100644 (file)
index 0000000..f620da5
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+       "net/http"
+       "strings"
+)
+
+// IsAPIPath returns true if the specified URL is an API path
+func IsAPIPath(req *http.Request) bool {
+       return strings.HasPrefix(req.URL.Path, "/api/")
+}
+
+// IsInternalPath returns true if the specified URL is an internal API path
+func IsInternalPath(req *http.Request) bool {
+       return strings.HasPrefix(req.URL.Path, "/api/internal/")
+}
index 701b3beed2113f16776783b8b12d925505a8b6d0..59e22c5be15f75b145f0ca382aceb208ce6d5df5 100644 (file)
@@ -11,7 +11,7 @@ import (
        "strings"
 
        "code.gitea.io/gitea/modules/context"
-       "code.gitea.io/gitea/modules/middlewares"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/binding"
        "github.com/go-chi/chi"
@@ -120,17 +120,17 @@ func Bind(obj interface{}) http.HandlerFunc {
                var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly
                binding.Bind(ctx.Req, theObj)
                SetForm(ctx, theObj)
-               middlewares.AssignForm(theObj, ctx.Data)
+               middleware.AssignForm(theObj, ctx.Data)
        })
 }
 
 // SetForm set the form object
-func SetForm(data middlewares.DataStore, obj interface{}) {
+func SetForm(data middleware.DataStore, obj interface{}) {
        data.GetData()["__form"] = obj
 }
 
 // GetForm returns the validate form information
-func GetForm(data middlewares.DataStore) interface{} {
+func GetForm(data middleware.DataStore) interface{} {
        return data.GetData()["__form"]
 }
 
index da2631931ebcbaa3665a33020beacece925d6d7a..69ae428a54894dae3fb0ed5f01ba4f81fe784fa3 100644 (file)
@@ -20,12 +20,12 @@ import (
        "code.gitea.io/gitea/modules/generate"
        "code.gitea.io/gitea/modules/graceful"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/templates"
        "code.gitea.io/gitea/modules/user"
        "code.gitea.io/gitea/modules/util"
        "code.gitea.io/gitea/modules/web"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/session"
        "gopkg.in/ini.v1"
@@ -47,11 +47,11 @@ func InstallInit(next http.Handler) http.Handler {
                        _ = rnd.HTML(resp, 200, string(tplPostInstall), nil)
                        return
                }
-               var locale = middlewares.Locale(resp, req)
+               var locale = middleware.Locale(resp, req)
                var startTime = time.Now()
                var ctx = context.Context{
                        Resp:    context.NewResponse(resp),
-                       Flash:   &middlewares.Flash{},
+                       Flash:   &middleware.Flash{},
                        Locale:  locale,
                        Render:  rnd,
                        Session: session.GetSession(req),
@@ -143,7 +143,7 @@ func Install(ctx *context.Context) {
        form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
        form.NoReplyAddress = setting.Service.NoReplyAddress
 
-       middlewares.AssignForm(form, ctx.Data)
+       middleware.AssignForm(form, ctx.Data)
        ctx.HTML(200, tplInstall)
 }
 
index 1862c15f4316c20db9c1eea89e19915f57ef51f1..69860021025b95b5096d9810af975ad975eef9c1 100644 (file)
@@ -21,7 +21,6 @@ import (
        auth "code.gitea.io/gitea/modules/forms"
        "code.gitea.io/gitea/modules/git"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/notification"
        repo_module "code.gitea.io/gitea/modules/repository"
        "code.gitea.io/gitea/modules/setting"
@@ -29,6 +28,7 @@ import (
        "code.gitea.io/gitea/modules/upload"
        "code.gitea.io/gitea/modules/util"
        "code.gitea.io/gitea/modules/web"
+       "code.gitea.io/gitea/modules/web/middleware"
        "code.gitea.io/gitea/routers/utils"
        "code.gitea.io/gitea/services/gitdiff"
        pull_service "code.gitea.io/gitea/services/pull"
@@ -989,7 +989,7 @@ func CompareAndPullRequestPost(ctx *context.Context) {
        }
 
        if ctx.HasError() {
-               middlewares.AssignForm(form, ctx.Data)
+               middleware.AssignForm(form, ctx.Data)
 
                // This stage is already stop creating new pull request, so it does not matter if it has
                // something to compare or not.
index 4efb7f01d5c75044846f2157485308f9ba5febfc..12a35936b10e4db6eaa436d43746cbf0fd22ac54 100644 (file)
@@ -18,10 +18,10 @@ import (
        "code.gitea.io/gitea/modules/context"
        "code.gitea.io/gitea/modules/httpcache"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/storage"
        "code.gitea.io/gitea/modules/templates"
+       "code.gitea.io/gitea/modules/web/middleware"
 
        "gitea.com/go-chi/session"
 )
@@ -153,7 +153,7 @@ func Recovery() func(next http.Handler) http.Handler {
                                                return
                                        }
 
-                                       var lc = middlewares.Locale(w, req)
+                                       var lc = middleware.Locale(w, req)
                                        var store = dataStore{
                                                Data: templates.Vars{
                                                        "Language":   lc.Language(),
index 0dc066d6000f986836eee14dfc9350cce20a3bac..fea396bc26c47c7d15dd038dced54ba5d38422fd 100644 (file)
@@ -11,11 +11,11 @@ import (
 
        "code.gitea.io/gitea/modules/forms"
        "code.gitea.io/gitea/modules/log"
-       "code.gitea.io/gitea/modules/middlewares"
        "code.gitea.io/gitea/modules/public"
        "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/templates"
        "code.gitea.io/gitea/modules/web"
+       "code.gitea.io/gitea/modules/web/middleware"
        "code.gitea.io/gitea/routers"
 
        "gitea.com/go-chi/session"
@@ -46,7 +46,7 @@ func installRecovery() func(next http.Handler) http.Handler {
                                        combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2)))
                                        log.Error("%v", combinedErr)
 
-                                       lc := middlewares.Locale(w, req)
+                                       lc := middleware.Locale(w, req)
                                        var store = dataStore{
                                                Data: templates.Vars{
                                                        "Language":       lc.Language(),
index 03555e3d547347b2480fa42f16350d6f6a0a20dc..f2b68aa10a57934104cacae2dc78bd473ab1b5ac 100644 (file)
@@ -247,7 +247,7 @@ func RegisterRoutes(m *web.Route) {
                }
        }
 
-       // FIXME: not all routes need go through same middlewares.
+       // FIXME: not all routes need go through same middleware.
        // Especially some AJAX requests, we can reduce middleware number to improve performance.
        // Routers.
        // for health check