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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. return tmplCtx
  84. }
  85. func NewWebContext(base *Base, render Render, session session.Store) *Context {
  86. ctx := &Context{
  87. Base: base,
  88. Render: render,
  89. Session: session,
  90. Cache: cache.GetCache(),
  91. Link: setting.AppSubURL + strings.TrimSuffix(base.Req.URL.EscapedPath(), "/"),
  92. Repo: &Repository{PullRequest: &PullRequest{}},
  93. Org: &Organization{},
  94. }
  95. ctx.TemplateContext = NewTemplateContextForWeb(ctx)
  96. ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}}
  97. return ctx
  98. }
  99. // Contexter initializes a classic context for a request.
  100. func Contexter() func(next http.Handler) http.Handler {
  101. rnd := templates.HTMLRenderer()
  102. csrfOpts := CsrfOptions{
  103. Secret: hex.EncodeToString(setting.GetGeneralTokenSigningSecret()),
  104. Cookie: setting.CSRFCookieName,
  105. SetCookie: true,
  106. Secure: setting.SessionConfig.Secure,
  107. CookieHTTPOnly: setting.CSRFCookieHTTPOnly,
  108. Header: "X-Csrf-Token",
  109. CookieDomain: setting.SessionConfig.Domain,
  110. CookiePath: setting.SessionConfig.CookiePath,
  111. SameSite: setting.SessionConfig.SameSite,
  112. }
  113. if !setting.IsProd {
  114. CsrfTokenRegenerationInterval = 5 * time.Second // in dev, re-generate the tokens more aggressively for debug purpose
  115. }
  116. return func(next http.Handler) http.Handler {
  117. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  118. base, baseCleanUp := NewBaseContext(resp, req)
  119. defer baseCleanUp()
  120. ctx := NewWebContext(base, rnd, session.GetSession(req))
  121. ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
  122. ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this
  123. ctx.Data["CurrentURL"] = setting.AppSubURL + req.URL.RequestURI()
  124. ctx.Data["Link"] = ctx.Link
  125. // PageData is passed by reference, and it will be rendered to `window.config.pageData` in `head.tmpl` for JavaScript modules
  126. ctx.PageData = map[string]any{}
  127. ctx.Data["PageData"] = ctx.PageData
  128. ctx.Base.AppendContextValue(WebContextKey, ctx)
  129. ctx.Base.AppendContextValueFunc(gitrepo.RepositoryContextKey, func() any { return ctx.Repo.GitRepo })
  130. ctx.Csrf = PrepareCSRFProtector(csrfOpts, ctx)
  131. // Get the last flash message from cookie
  132. lastFlashCookie := middleware.GetSiteCookie(ctx.Req, CookieNameFlash)
  133. if vals, _ := url.ParseQuery(lastFlashCookie); len(vals) > 0 {
  134. // store last Flash message into the template data, to render it
  135. ctx.Data["Flash"] = &middleware.Flash{
  136. DataStore: ctx,
  137. Values: vals,
  138. ErrorMsg: vals.Get("error"),
  139. SuccessMsg: vals.Get("success"),
  140. InfoMsg: vals.Get("info"),
  141. WarningMsg: vals.Get("warning"),
  142. }
  143. }
  144. // if there are new messages in the ctx.Flash, write them into cookie
  145. ctx.Resp.Before(func(resp ResponseWriter) {
  146. if val := ctx.Flash.Encode(); val != "" {
  147. middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, val, 0)
  148. } else if lastFlashCookie != "" {
  149. middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, "", -1)
  150. }
  151. })
  152. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  153. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  154. if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  155. ctx.ServerError("ParseMultipartForm", err)
  156. return
  157. }
  158. }
  159. httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
  160. ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  161. ctx.Data["SystemConfig"] = setting.Config()
  162. ctx.Data["CsrfToken"] = ctx.Csrf.GetToken()
  163. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  164. // FIXME: do we really always need these setting? There should be someway to have to avoid having to always set these
  165. ctx.Data["DisableMigrations"] = setting.Repository.DisableMigrations
  166. ctx.Data["DisableStars"] = setting.Repository.DisableStars
  167. ctx.Data["EnableActions"] = setting.Actions.Enabled
  168. ctx.Data["ManifestData"] = setting.ManifestData
  169. ctx.Data["UnitWikiGlobalDisabled"] = unit.TypeWiki.UnitGlobalDisabled()
  170. ctx.Data["UnitIssuesGlobalDisabled"] = unit.TypeIssues.UnitGlobalDisabled()
  171. ctx.Data["UnitPullsGlobalDisabled"] = unit.TypePullRequests.UnitGlobalDisabled()
  172. ctx.Data["UnitProjectsGlobalDisabled"] = unit.TypeProjects.UnitGlobalDisabled()
  173. ctx.Data["UnitActionsGlobalDisabled"] = unit.TypeActions.UnitGlobalDisabled()
  174. ctx.Data["AllLangs"] = translation.AllLangs()
  175. next.ServeHTTP(ctx.Resp, ctx.Req)
  176. })
  177. }
  178. }
  179. // HasError returns true if error occurs in form validation.
  180. // Attention: this function changes ctx.Data and ctx.Flash
  181. func (ctx *Context) HasError() bool {
  182. hasErr, ok := ctx.Data["HasError"]
  183. if !ok {
  184. return false
  185. }
  186. ctx.Flash.ErrorMsg = ctx.GetErrMsg()
  187. ctx.Data["Flash"] = ctx.Flash
  188. return hasErr.(bool)
  189. }
  190. // GetErrMsg returns error message in form validation.
  191. func (ctx *Context) GetErrMsg() string {
  192. msg, _ := ctx.Data["ErrorMsg"].(string)
  193. if msg == "" {
  194. msg = "invalid form data"
  195. }
  196. return msg
  197. }
  198. func (ctx *Context) JSONRedirect(redirect string) {
  199. ctx.JSON(http.StatusOK, map[string]any{"redirect": redirect})
  200. }
  201. func (ctx *Context) JSONOK() {
  202. ctx.JSON(http.StatusOK, map[string]any{"ok": true}) // this is only a dummy response, frontend seldom uses it
  203. }
  204. func (ctx *Context) JSONError(msg any) {
  205. switch v := msg.(type) {
  206. case string:
  207. ctx.JSON(http.StatusBadRequest, map[string]any{"errorMessage": v, "renderFormat": "text"})
  208. case template.HTML:
  209. ctx.JSON(http.StatusBadRequest, map[string]any{"errorMessage": v, "renderFormat": "html"})
  210. default:
  211. panic(fmt.Sprintf("unsupported type: %T", msg))
  212. }
  213. }