From 37b29319aaab085001def4bc33b690c9a7a8eb19 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 28 Sep 2021 21:13:04 +0800 Subject: [PATCH] Fix bug of get context user (#17169) Co-authored-by: 6543 <6543@obermui.de> --- modules/context/context.go | 11 +++++++++++ routers/web/base.go | 11 +---------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/modules/context/context.go b/modules/context/context.go index 3dbc2bb9dc..bed4760322 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -547,6 +547,17 @@ func GetContext(req *http.Request) *Context { return req.Context().Value(contextKey).(*Context) } +// GetContextUser returns context user +func GetContextUser(req *http.Request) *models.User { + if apiContext, ok := req.Context().Value(apiContextKey).(*APIContext); ok { + return apiContext.User + } + if ctx, ok := req.Context().Value(contextKey).(*Context); ok { + return ctx.User + } + return nil +} + // SignedUserName returns signed user's name via context func SignedUserName(req *http.Request) string { if middleware.IsInternalPath(req) { diff --git a/routers/web/base.go b/routers/web/base.go index 9238ea2173..f50c5229b1 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -14,7 +14,6 @@ import ( "path/filepath" "strings" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -147,15 +146,7 @@ func Recovery() func(next http.Handler) http.Handler { "i18n": lc, } - var user *models.User - if apiContext := context.GetAPIContext(req); apiContext != nil { - user = apiContext.User - } - if user == nil { - if ctx := context.GetContext(req); ctx != nil { - user = ctx.User - } - } + var user = context.GetContextUser(req) if user == nil { // Get user from session if logged in - do not attempt to sign-in user = auth.SessionUser(sessionStore)