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.

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