gitea源码

base.go 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "fmt"
  6. "html/template"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "code.gitea.io/gitea/modules/httplib"
  12. "code.gitea.io/gitea/modules/json"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/reqctx"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/translation"
  17. "code.gitea.io/gitea/modules/web/middleware"
  18. )
  19. type BaseContextKeyType struct{}
  20. var BaseContextKey BaseContextKeyType
  21. // Base is the base context for all web handlers
  22. // ATTENTION: This struct should never be manually constructed in routes/services,
  23. // it has many internal details which should be carefully prepared by the framework.
  24. // If it is abused, it would cause strange bugs like panic/resource-leak.
  25. type Base struct {
  26. reqctx.RequestContext
  27. Resp ResponseWriter
  28. Req *http.Request
  29. // Data is prepared by ContextDataStore middleware, this field only refers to the pre-created/prepared ContextData.
  30. // Although it's mainly used for MVC templates, sometimes it's also used to pass data between middlewares/handler
  31. Data reqctx.ContextData
  32. // Locale is mainly for Web context, although the API context also uses it in some cases: message response, form validation
  33. Locale translation.Locale
  34. }
  35. // AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header
  36. func (b *Base) AppendAccessControlExposeHeaders(names ...string) {
  37. val := b.RespHeader().Get("Access-Control-Expose-Headers")
  38. if len(val) != 0 {
  39. b.RespHeader().Set("Access-Control-Expose-Headers", fmt.Sprintf("%s, %s", val, strings.Join(names, ", ")))
  40. } else {
  41. b.RespHeader().Set("Access-Control-Expose-Headers", strings.Join(names, ", "))
  42. }
  43. }
  44. // SetTotalCountHeader set "X-Total-Count" header
  45. func (b *Base) SetTotalCountHeader(total int64) {
  46. b.RespHeader().Set("X-Total-Count", strconv.FormatInt(total, 10))
  47. b.AppendAccessControlExposeHeaders("X-Total-Count")
  48. }
  49. // Written returns true if there are something sent to web browser
  50. func (b *Base) Written() bool {
  51. return b.Resp.WrittenStatus() != 0
  52. }
  53. func (b *Base) WrittenStatus() int {
  54. return b.Resp.WrittenStatus()
  55. }
  56. // Status writes status code
  57. func (b *Base) Status(status int) {
  58. b.Resp.WriteHeader(status)
  59. }
  60. // Write writes data to web browser
  61. func (b *Base) Write(bs []byte) (int, error) {
  62. return b.Resp.Write(bs)
  63. }
  64. // RespHeader returns the response header
  65. func (b *Base) RespHeader() http.Header {
  66. return b.Resp.Header()
  67. }
  68. // HTTPError returned an error to web browser
  69. // FIXME: many calls to this HTTPError are not right: it shouldn't expose err.Error() directly, it doesn't accept more than one content
  70. func (b *Base) HTTPError(status int, contents ...string) {
  71. v := http.StatusText(status)
  72. if len(contents) > 0 {
  73. v = contents[0]
  74. }
  75. http.Error(b.Resp, v, status)
  76. }
  77. // JSON render content as JSON
  78. func (b *Base) JSON(status int, content any) {
  79. b.Resp.Header().Set("Content-Type", "application/json;charset=utf-8")
  80. b.Resp.WriteHeader(status)
  81. if err := json.NewEncoder(b.Resp).Encode(content); err != nil {
  82. log.Error("Render JSON failed: %v", err)
  83. }
  84. }
  85. // RemoteAddr returns the client machine ip address
  86. func (b *Base) RemoteAddr() string {
  87. return b.Req.RemoteAddr
  88. }
  89. // PlainTextBytes renders bytes as plain text
  90. func (b *Base) plainTextInternal(skip, status int, bs []byte) {
  91. statusPrefix := status / 100
  92. if statusPrefix == 4 || statusPrefix == 5 {
  93. log.Log(skip, log.TRACE, "plainTextInternal (status=%d): %s", status, string(bs))
  94. }
  95. b.Resp.Header().Set("Content-Type", "text/plain;charset=utf-8")
  96. b.Resp.Header().Set("X-Content-Type-Options", "nosniff")
  97. b.Resp.WriteHeader(status)
  98. _, _ = b.Resp.Write(bs)
  99. }
  100. // PlainTextBytes renders bytes as plain text
  101. func (b *Base) PlainTextBytes(status int, bs []byte) {
  102. b.plainTextInternal(2, status, bs)
  103. }
  104. // PlainText renders content as plain text
  105. func (b *Base) PlainText(status int, text string) {
  106. b.plainTextInternal(2, status, []byte(text))
  107. }
  108. // Redirect redirects the request
  109. func (b *Base) Redirect(location string, status ...int) {
  110. code := http.StatusSeeOther
  111. if len(status) == 1 {
  112. code = status[0]
  113. }
  114. if !httplib.IsRelativeURL(location) {
  115. // Some browsers (Safari) have buggy behavior for Cookie + Cache + External Redirection, eg: /my-path => https://other/path
  116. // 1. the first request to "/my-path" contains cookie
  117. // 2. some time later, the request to "/my-path" doesn't contain cookie (caused by Prevent web tracking)
  118. // 3. Gitea's Sessioner doesn't see the session cookie, so it generates a new session id, and returns it to browser
  119. // 4. then the browser accepts the empty session, then the user is logged out
  120. // So in this case, we should remove the session cookie from the response header
  121. removeSessionCookieHeader(b.Resp)
  122. }
  123. // in case the request is made by htmx, have it redirect the browser instead of trying to follow the redirect inside htmx
  124. if b.Req.Header.Get("HX-Request") == "true" {
  125. b.Resp.Header().Set("HX-Redirect", location)
  126. // we have to return a non-redirect status code so XMLHTTPRequest will not immediately follow the redirect
  127. // so as to give htmx redirect logic a chance to run
  128. b.Status(http.StatusNoContent)
  129. return
  130. }
  131. http.Redirect(b.Resp, b.Req, location, code)
  132. }
  133. type ServeHeaderOptions httplib.ServeHeaderOptions
  134. func (b *Base) SetServeHeaders(opt *ServeHeaderOptions) {
  135. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opt))
  136. }
  137. // ServeContent serves content to http request
  138. func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) {
  139. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opts))
  140. http.ServeContent(b.Resp, b.Req, opts.Filename, opts.LastModified, r)
  141. }
  142. func (b *Base) Tr(msg string, args ...any) template.HTML {
  143. return b.Locale.Tr(msg, args...)
  144. }
  145. func (b *Base) TrN(cnt any, key1, keyN string, args ...any) template.HTML {
  146. return b.Locale.TrN(cnt, key1, keyN, args...)
  147. }
  148. func NewBaseContext(resp http.ResponseWriter, req *http.Request) *Base {
  149. reqCtx := reqctx.FromContext(req.Context())
  150. b := &Base{
  151. RequestContext: reqCtx,
  152. Req: req,
  153. Resp: WrapResponseWriter(resp),
  154. Locale: middleware.Locale(resp, req),
  155. Data: reqCtx.GetData(),
  156. }
  157. b.Req = b.Req.WithContext(b)
  158. reqCtx.SetContextValue(BaseContextKey, b)
  159. reqCtx.SetContextValue(translation.ContextKey, b.Locale)
  160. reqCtx.SetContextValue(httplib.RequestContextKey, b.Req)
  161. return b
  162. }
  163. func NewBaseContextForTest(resp http.ResponseWriter, req *http.Request) *Base {
  164. if !setting.IsInTesting {
  165. panic("This function is only for testing")
  166. }
  167. ctx := reqctx.NewRequestContextForTest(req.Context())
  168. *req = *req.WithContext(ctx)
  169. return NewBaseContext(resp, req)
  170. }