You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package context
  5. import (
  6. "context"
  7. "encoding/hex"
  8. "fmt"
  9. "html/template"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/models/unit"
  16. user_model "code.gitea.io/gitea/models/user"
  17. "code.gitea.io/gitea/modules/cache"
  18. "code.gitea.io/gitea/modules/gitrepo"
  19. "code.gitea.io/gitea/modules/httpcache"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates"
  22. "code.gitea.io/gitea/modules/translation"
  23. "code.gitea.io/gitea/modules/web"
  24. "code.gitea.io/gitea/modules/web/middleware"
  25. web_types "code.gitea.io/gitea/modules/web/types"
  26. "gitea.com/go-chi/session"
  27. )
  28. // Render represents a template render
  29. type Render interface {
  30. TemplateLookup(tmpl string, templateCtx context.Context) (templates.TemplateExecutor, error)
  31. HTML(w io.Writer, status int, name string, data any, templateCtx context.Context) error
  32. }
  33. // Context represents context of a request.
  34. type Context struct {
  35. *Base
  36. TemplateContext TemplateContext
  37. Render Render
  38. PageData map[string]any // data used by JavaScript modules in one page, it's `window.config.pageData`
  39. Cache cache.StringCache
  40. Csrf CSRFProtector
  41. Flash *middleware.Flash
  42. Session session.Store
  43. Link string // current request URL (without query string)
  44. Doer *user_model.User // current signed-in user
  45. IsSigned bool
  46. IsBasicAuth bool
  47. ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
  48. Repo *Repository
  49. Org *Organization
  50. Package *Package
  51. }
  52. type TemplateContext map[string]any
  53. func init() {
  54. web.RegisterResponseStatusProvider[*Context](func(req *http.Request) web_types.ResponseStatusProvider {
  55. return req.Context().Value(WebContextKey).(*Context)
  56. })
  57. }
  58. type webContextKeyType struct{}
  59. var WebContextKey = webContextKeyType{}
  60. func GetWebContext(req *http.Request) *Context {
  61. ctx, _ := req.Context().Value(WebContextKey).(*Context)
  62. return ctx
  63. }
  64. // ValidateContext is a special context for form validation middleware. It may be different from other contexts.
  65. type ValidateContext struct {
  66. *Base
  67. }
  68. // GetValidateContext gets a context for middleware form validation
  69. func GetValidateContext(req *http.Request) (ctx *ValidateContext) {
  70. if ctxAPI, ok := req.Context().Value(apiContextKey).(*APIContext); ok {
  71. ctx = &ValidateContext{Base: ctxAPI.Base}
  72. } else if ctxWeb, ok := req.Context().Value(WebContextKey).(*Context); ok {
  73. ctx = &ValidateContext{Base: ctxWeb.Base}
  74. } else {
  75. panic("invalid context, expect either APIContext or Context")
  76. }
  77. return ctx
  78. }
  79. func NewTemplateContextForWeb(ctx *Context) TemplateContext {
  80. tmplCtx := NewTemplateContext(ctx)
  81. tmplCtx["Locale"] = ctx.Base.Locale
  82. tmplCtx["AvatarUtils"] = templates.NewAvatarUtils(ctx)
  83. tmplCtx["RootData"] = ctx.Data
  84. return tmplCtx
  85. }
  86. func NewWebContext(base *Base, render Render, session session.Store) *Context {
  87. ctx := &Context{
  88. Base: base,
  89. Render: render,
  90. Session: session,
  91. Cache: cache.GetCache(),
  92. Link: setting.AppSubURL + strings.TrimSuffix(base.Req.URL.EscapedPath(), "/"),
  93. Repo: &Repository{PullRequest: &PullRequest{}},
  94. Org: &Organization{},
  95. }
  96. ctx.TemplateContext = NewTemplateContextForWeb(ctx)
  97. ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}}
  98. return ctx
  99. }
  100. // Contexter initializes a classic context for a request.
  101. func Contexter() func(next http.Handler) http.Handler {
  102. rnd := templates.HTMLRenderer()
  103. csrfOpts := CsrfOptions{
  104. Secret: hex.EncodeToString(setting.GetGeneralTokenSigningSecret()),
  105. Cookie: setting.CSRFCookieName,
  106. SetCookie: true,
  107. Secure: setting.SessionConfig.Secure,
  108. CookieHTTPOnly: setting.CSRFCookieHTTPOnly,
  109. Header: "X-Csrf-Token",
  110. CookieDomain: setting.SessionConfig.Domain,
  111. CookiePath: setting.SessionConfig.CookiePath,
  112. SameSite: setting.SessionConfig.SameSite,
  113. }
  114. if !setting.IsProd {
  115. CsrfTokenRegenerationInterval = 5 * time.Second // in dev, re-generate the tokens more aggressively for debug purpose
  116. }
  117. return func(next http.Handler) http.Handler {
  118. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  119. base, baseCleanUp := NewBaseContext(resp, req)
  120. defer baseCleanUp()
  121. ctx := NewWebContext(base, rnd, session.GetSession(req))
  122. ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
  123. ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this
  124. ctx.Data["CurrentURL"] = setting.AppSubURL + req.URL.RequestURI()
  125. ctx.Data["Link"] = ctx.Link
  126. // PageData is passed by reference, and it will be rendered to `window.config.pageData` in `head.tmpl` for JavaScript modules
  127. ctx.PageData = map[string]any{}
  128. ctx.Data["PageData"] = ctx.PageData
  129. ctx.Base.AppendContextValue(WebContextKey, ctx)
  130. ctx.Base.AppendContextValueFunc(gitrepo.RepositoryContextKey, func() any { return ctx.Repo.GitRepo })
  131. ctx.Csrf = PrepareCSRFProtector(csrfOpts, ctx)
  132. // Get the last flash message from cookie
  133. lastFlashCookie := middleware.GetSiteCookie(ctx.Req, CookieNameFlash)
  134. if vals, _ := url.ParseQuery(lastFlashCookie); len(vals) > 0 {
  135. // store last Flash message into the template data, to render it
  136. ctx.Data["Flash"] = &middleware.Flash{
  137. DataStore: ctx,
  138. Values: vals,
  139. ErrorMsg: vals.Get("error"),
  140. SuccessMsg: vals.Get("success"),
  141. InfoMsg: vals.Get("info"),
  142. WarningMsg: vals.Get("warning"),
  143. }
  144. }
  145. // if there are new messages in the ctx.Flash, write them into cookie
  146. ctx.Resp.Before(func(resp ResponseWriter) {
  147. if val := ctx.Flash.Encode(); val != "" {
  148. middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, val, 0)
  149. } else if lastFlashCookie != "" {
  150. middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, "", -1)
  151. }
  152. })
  153. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  154. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  155. if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  156. ctx.ServerError("ParseMultipartForm", err)
  157. return
  158. }
  159. }
  160. httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
  161. ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  162. ctx.Data["SystemConfig"] = setting.Config()
  163. ctx.Data["CsrfToken"] = ctx.Csrf.GetToken()
  164. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  165. // FIXME: do we really always need these setting? There should be someway to have to avoid having to always set these
  166. ctx.Data["DisableMigrations"] = setting.Repository.DisableMigrations
  167. ctx.Data["DisableStars"] = setting.Repository.DisableStars
  168. ctx.Data["EnableActions"] = setting.Actions.Enabled
  169. ctx.Data["ManifestData"] = setting.ManifestData
  170. ctx.Data["UnitWikiGlobalDisabled"] = unit.TypeWiki.UnitGlobalDisabled()
  171. ctx.Data["UnitIssuesGlobalDisabled"] = unit.TypeIssues.UnitGlobalDisabled()
  172. ctx.Data["UnitPullsGlobalDisabled"] = unit.TypePullRequests.UnitGlobalDisabled()
  173. ctx.Data["UnitProjectsGlobalDisabled"] = unit.TypeProjects.UnitGlobalDisabled()
  174. ctx.Data["UnitActionsGlobalDisabled"] = unit.TypeActions.UnitGlobalDisabled()
  175. ctx.Data["AllLangs"] = translation.AllLangs()
  176. next.ServeHTTP(ctx.Resp, ctx.Req)
  177. })
  178. }
  179. }
  180. // HasError returns true if error occurs in form validation.
  181. // Attention: this function changes ctx.Data and ctx.Flash
  182. func (ctx *Context) HasError() bool {
  183. hasErr, ok := ctx.Data["HasError"]
  184. if !ok {
  185. return false
  186. }
  187. ctx.Flash.ErrorMsg = ctx.GetErrMsg()
  188. ctx.Data["Flash"] = ctx.Flash
  189. return hasErr.(bool)
  190. }
  191. // GetErrMsg returns error message in form validation.
  192. func (ctx *Context) GetErrMsg() string {
  193. msg, _ := ctx.Data["ErrorMsg"].(string)
  194. if msg == "" {
  195. msg = "invalid form data"
  196. }
  197. return msg
  198. }
  199. func (ctx *Context) JSONRedirect(redirect string) {
  200. ctx.JSON(http.StatusOK, map[string]any{"redirect": redirect})
  201. }
  202. func (ctx *Context) JSONOK() {
  203. ctx.JSON(http.StatusOK, map[string]any{"ok": true}) // this is only a dummy response, frontend seldom uses it
  204. }
  205. func (ctx *Context) JSONError(msg any) {
  206. switch v := msg.(type) {
  207. case string:
  208. ctx.JSON(http.StatusBadRequest, map[string]any{"errorMessage": v, "renderFormat": "text"})
  209. case template.HTML:
  210. ctx.JSON(http.StatusBadRequest, map[string]any{"errorMessage": v, "renderFormat": "html"})
  211. default:
  212. panic(fmt.Sprintf("unsupported type: %T", msg))
  213. }
  214. }