Fix context usage (#33554)

Some old code use direct type-casting to get context, it causes
problems.

This PR fixes all legacy problems and use correct `ctx.Value` to get
low-level contexts.

Fix #33518
pull/33543/head^2
wxiaoguang 2 weeks ago committed by GitHub
parent e9b98aef44
commit 245ac321c3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -64,7 +64,7 @@ func Contexter() func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
base := context.NewBaseContext(resp, req) base := context.NewBaseContext(resp, req)
ctx := context.NewWebContext(base, rnd, session.GetSession(req)) ctx := context.NewWebContext(base, rnd, session.GetSession(req))
ctx.SetContextValue(context.WebContextKey, ctx) ctx.SetContextValue(context.WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
ctx.Data.MergeFrom(middleware.CommonTemplateContextData()) ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
ctx.Data.MergeFrom(reqctx.ContextData{ ctx.Data.MergeFrom(reqctx.ContextData{
"Title": ctx.Locale.Tr("install.install"), "Title": ctx.Locale.Tr("install.install"),

@ -88,7 +88,7 @@ func Routes() *web.Router {
// Fortunately, the LFS handlers are able to handle requests without a complete web context // Fortunately, the LFS handlers are able to handle requests without a complete web context
common.AddOwnerRepoGitLFSRoutes(r, func(ctx *context.PrivateContext) { common.AddOwnerRepoGitLFSRoutes(r, func(ctx *context.PrivateContext) {
webContext := &context.Context{Base: ctx.Base} webContext := &context.Context{Base: ctx.Base}
ctx.SetContextValue(context.WebContextKey, webContext) ctx.SetContextValue(context.WebContextKey, webContext) // FIXME: this is not ideal but no other way at the moment
}) })
}) })

@ -1637,7 +1637,7 @@ func registerRoutes(m *web.Router) {
} }
m.NotFound(func(w http.ResponseWriter, req *http.Request) { m.NotFound(func(w http.ResponseWriter, req *http.Request) {
ctx := context.GetWebContext(req) ctx := context.GetWebContext(req.Context())
defer routing.RecordFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))() defer routing.RecordFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))()
ctx.NotFound("", nil) ctx.NotFound("", nil)
}) })

@ -149,7 +149,7 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
middleware.SetLocaleCookie(resp, user.Language, 0) middleware.SetLocaleCookie(resp, user.Language, 0)
// force to generate a new CSRF token // force to generate a new CSRF token
if ctx := gitea_context.GetWebContext(req); ctx != nil { if ctx := gitea_context.GetWebContext(req.Context()); ctx != nil {
ctx.Csrf.PrepareForSessionUser(ctx) ctx.Csrf.PrepareForSessionUser(ctx)
} }
} }

@ -88,7 +88,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
store.GetData()["EnableSSPI"] = true store.GetData()["EnableSSPI"] = true
// in this case, the Verify function is called in Gitea's web context // in this case, the Verify function is called in Gitea's web context
// FIXME: it doesn't look good to render the page here, why not redirect? // FIXME: it doesn't look good to render the page here, why not redirect?
gitea_context.GetWebContext(req).HTML(http.StatusUnauthorized, tplSignIn) gitea_context.GetWebContext(req.Context()).HTML(http.StatusUnauthorized, tplSignIn)
return nil, err return nil, err
} }
if outToken != "" { if outToken != "" {

@ -79,9 +79,9 @@ type webContextKeyType struct{}
var WebContextKey = webContextKeyType{} var WebContextKey = webContextKeyType{}
func GetWebContext(req *http.Request) *Context { func GetWebContext(ctx context.Context) *Context {
ctx, _ := req.Context().Value(WebContextKey).(*Context) webCtx, _ := ctx.Value(WebContextKey).(*Context)
return ctx return webCtx
} }
// ValidateContext is a special context for form validation middleware. It may be different from other contexts. // ValidateContext is a special context for form validation middleware. It may be different from other contexts.
@ -135,6 +135,7 @@ func NewWebContext(base *Base, render Render, session session.Store) *Context {
} }
ctx.TemplateContext = NewTemplateContextForWeb(ctx) ctx.TemplateContext = NewTemplateContextForWeb(ctx)
ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}} ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}}
ctx.SetContextValue(WebContextKey, ctx)
return ctx return ctx
} }
@ -165,7 +166,7 @@ func Contexter() func(next http.Handler) http.Handler {
ctx.PageData = map[string]any{} ctx.PageData = map[string]any{}
ctx.Data["PageData"] = ctx.PageData ctx.Data["PageData"] = ctx.PageData
ctx.Base.SetContextValue(WebContextKey, ctx) ctx.Base.SetContextValue(WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
ctx.Csrf = NewCSRFProtector(csrfOpts) ctx.Csrf = NewCSRFProtector(csrfOpts)
// get the last flash message from cookie // get the last flash message from cookie

@ -156,7 +156,7 @@ func PackageContexter() func(next http.Handler) http.Handler {
base := NewBaseContext(resp, req) base := NewBaseContext(resp, req)
// it is still needed when rendering 500 page in a package handler // it is still needed when rendering 500 page in a package handler
ctx := NewWebContext(base, renderer, nil) ctx := NewWebContext(base, renderer, nil)
ctx.SetContextValue(WebContextKey, ctx) ctx.SetContextValue(WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
next.ServeHTTP(ctx.Resp, ctx.Req) next.ServeHTTP(ctx.Resp, ctx.Req)
}) })
} }

@ -67,7 +67,7 @@ func MockContext(t *testing.T, reqPath string, opts ...MockContextOption) (*cont
chiCtx := chi.NewRouteContext() chiCtx := chi.NewRouteContext()
ctx := context.NewWebContext(base, opt.Render, nil) ctx := context.NewWebContext(base, opt.Render, nil)
ctx.SetContextValue(context.WebContextKey, ctx) ctx.SetContextValue(context.WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
ctx.SetContextValue(chi.RouteCtxKey, chiCtx) ctx.SetContextValue(chi.RouteCtxKey, chiCtx)
if opt.SessionStore != nil { if opt.SessionStore != nil {
ctx.SetContextValue(session.MockStoreContextKey, opt.SessionStore) ctx.SetContextValue(session.MockStoreContextKey, opt.SessionStore)

@ -21,8 +21,8 @@ func FormalRenderHelperFuncs() *markup.RenderHelperFuncs {
return false return false
} }
giteaCtx, ok := ctx.(*gitea_context.Context) giteaCtx := gitea_context.GetWebContext(ctx)
if !ok { if giteaCtx == nil {
// when using general context, use user's visibility to check // when using general context, use user's visibility to check
return mentionedUser.Visibility.IsPublic() return mentionedUser.Visibility.IsPublic()
} }

@ -36,8 +36,8 @@ func renderRepoFileCodePreview(ctx context.Context, opts markup.RenderCodePrevie
return "", err return "", err
} }
webCtx, ok := ctx.Value(gitea_context.WebContextKey).(*gitea_context.Context) webCtx := gitea_context.GetWebContext(ctx)
if !ok { if webCtx == nil {
return "", fmt.Errorf("context is not a web context") return "", fmt.Errorf("context is not a web context")
} }
doer := webCtx.Doer doer := webCtx.Doer

@ -18,8 +18,8 @@ import (
) )
func renderRepoIssueIconTitle(ctx context.Context, opts markup.RenderIssueIconTitleOptions) (_ template.HTML, err error) { func renderRepoIssueIconTitle(ctx context.Context, opts markup.RenderIssueIconTitleOptions) (_ template.HTML, err error) {
webCtx, ok := ctx.Value(gitea_context.WebContextKey).(*gitea_context.Context) webCtx := gitea_context.GetWebContext(ctx)
if !ok { if webCtx == nil {
return "", fmt.Errorf("context is not a web context") return "", fmt.Errorf("context is not a web context")
} }

Loading…
Cancel
Save