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.

base.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "context"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/modules/httplib"
  14. "code.gitea.io/gitea/modules/json"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/translation"
  17. "code.gitea.io/gitea/modules/util"
  18. "code.gitea.io/gitea/modules/web/middleware"
  19. "github.com/go-chi/chi/v5"
  20. )
  21. type contextValuePair struct {
  22. key any
  23. valueFn func() any
  24. }
  25. type Base struct {
  26. originCtx context.Context
  27. contextValues []contextValuePair
  28. Resp ResponseWriter
  29. Req *http.Request
  30. // Data is prepared by ContextDataStore middleware, this field only refers to the pre-created/prepared ContextData.
  31. // Although it's mainly used for MVC templates, sometimes it's also used to pass data between middlewares/handler
  32. Data middleware.ContextData
  33. // Locale is mainly for Web context, although the API context also uses it in some cases: message response, form validation
  34. Locale translation.Locale
  35. }
  36. func (b *Base) Deadline() (deadline time.Time, ok bool) {
  37. return b.originCtx.Deadline()
  38. }
  39. func (b *Base) Done() <-chan struct{} {
  40. return b.originCtx.Done()
  41. }
  42. func (b *Base) Err() error {
  43. return b.originCtx.Err()
  44. }
  45. func (b *Base) Value(key any) any {
  46. for _, pair := range b.contextValues {
  47. if pair.key == key {
  48. return pair.valueFn()
  49. }
  50. }
  51. return b.originCtx.Value(key)
  52. }
  53. func (b *Base) AppendContextValueFunc(key any, valueFn func() any) any {
  54. b.contextValues = append(b.contextValues, contextValuePair{key, valueFn})
  55. return b
  56. }
  57. func (b *Base) AppendContextValue(key, value any) any {
  58. b.contextValues = append(b.contextValues, contextValuePair{key, func() any { return value }})
  59. return b
  60. }
  61. func (b *Base) GetData() middleware.ContextData {
  62. return b.Data
  63. }
  64. // AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header
  65. func (b *Base) AppendAccessControlExposeHeaders(names ...string) {
  66. val := b.RespHeader().Get("Access-Control-Expose-Headers")
  67. if len(val) != 0 {
  68. b.RespHeader().Set("Access-Control-Expose-Headers", fmt.Sprintf("%s, %s", val, strings.Join(names, ", ")))
  69. } else {
  70. b.RespHeader().Set("Access-Control-Expose-Headers", strings.Join(names, ", "))
  71. }
  72. }
  73. // SetTotalCountHeader set "X-Total-Count" header
  74. func (b *Base) SetTotalCountHeader(total int64) {
  75. b.RespHeader().Set("X-Total-Count", fmt.Sprint(total))
  76. b.AppendAccessControlExposeHeaders("X-Total-Count")
  77. }
  78. // Written returns true if there are something sent to web browser
  79. func (b *Base) Written() bool {
  80. return b.Resp.Status() > 0
  81. }
  82. // Status writes status code
  83. func (b *Base) Status(status int) {
  84. b.Resp.WriteHeader(status)
  85. }
  86. // Write writes data to web browser
  87. func (b *Base) Write(bs []byte) (int, error) {
  88. return b.Resp.Write(bs)
  89. }
  90. // RespHeader returns the response header
  91. func (b *Base) RespHeader() http.Header {
  92. return b.Resp.Header()
  93. }
  94. // Error returned an error to web browser
  95. func (b *Base) Error(status int, contents ...string) {
  96. v := http.StatusText(status)
  97. if len(contents) > 0 {
  98. v = contents[0]
  99. }
  100. http.Error(b.Resp, v, status)
  101. }
  102. // JSON render content as JSON
  103. func (b *Base) JSON(status int, content interface{}) {
  104. b.Resp.Header().Set("Content-Type", "application/json;charset=utf-8")
  105. b.Resp.WriteHeader(status)
  106. if err := json.NewEncoder(b.Resp).Encode(content); err != nil {
  107. log.Error("Render JSON failed: %v", err)
  108. }
  109. }
  110. // RemoteAddr returns the client machine ip address
  111. func (b *Base) RemoteAddr() string {
  112. return b.Req.RemoteAddr
  113. }
  114. // Params returns the param on route
  115. func (b *Base) Params(p string) string {
  116. s, _ := url.PathUnescape(chi.URLParam(b.Req, strings.TrimPrefix(p, ":")))
  117. return s
  118. }
  119. // ParamsInt64 returns the param on route as int64
  120. func (b *Base) ParamsInt64(p string) int64 {
  121. v, _ := strconv.ParseInt(b.Params(p), 10, 64)
  122. return v
  123. }
  124. // SetParams set params into routes
  125. func (b *Base) SetParams(k, v string) {
  126. chiCtx := chi.RouteContext(b)
  127. chiCtx.URLParams.Add(strings.TrimPrefix(k, ":"), url.PathEscape(v))
  128. }
  129. // FormString returns the first value matching the provided key in the form as a string
  130. func (b *Base) FormString(key string) string {
  131. return b.Req.FormValue(key)
  132. }
  133. // FormStrings returns a string slice for the provided key from the form
  134. func (b *Base) FormStrings(key string) []string {
  135. if b.Req.Form == nil {
  136. if err := b.Req.ParseMultipartForm(32 << 20); err != nil {
  137. return nil
  138. }
  139. }
  140. if v, ok := b.Req.Form[key]; ok {
  141. return v
  142. }
  143. return nil
  144. }
  145. // FormTrim returns the first value for the provided key in the form as a space trimmed string
  146. func (b *Base) FormTrim(key string) string {
  147. return strings.TrimSpace(b.Req.FormValue(key))
  148. }
  149. // FormInt returns the first value for the provided key in the form as an int
  150. func (b *Base) FormInt(key string) int {
  151. v, _ := strconv.Atoi(b.Req.FormValue(key))
  152. return v
  153. }
  154. // FormInt64 returns the first value for the provided key in the form as an int64
  155. func (b *Base) FormInt64(key string) int64 {
  156. v, _ := strconv.ParseInt(b.Req.FormValue(key), 10, 64)
  157. return v
  158. }
  159. // FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
  160. func (b *Base) FormBool(key string) bool {
  161. s := b.Req.FormValue(key)
  162. v, _ := strconv.ParseBool(s)
  163. v = v || strings.EqualFold(s, "on")
  164. return v
  165. }
  166. // FormOptionalBool returns an OptionalBoolTrue or OptionalBoolFalse if the value
  167. // for the provided key exists in the form else it returns OptionalBoolNone
  168. func (b *Base) FormOptionalBool(key string) util.OptionalBool {
  169. value := b.Req.FormValue(key)
  170. if len(value) == 0 {
  171. return util.OptionalBoolNone
  172. }
  173. s := b.Req.FormValue(key)
  174. v, _ := strconv.ParseBool(s)
  175. v = v || strings.EqualFold(s, "on")
  176. return util.OptionalBoolOf(v)
  177. }
  178. func (b *Base) SetFormString(key, value string) {
  179. _ = b.Req.FormValue(key) // force parse form
  180. b.Req.Form.Set(key, value)
  181. }
  182. // PlainTextBytes renders bytes as plain text
  183. func (b *Base) plainTextInternal(skip, status int, bs []byte) {
  184. statusPrefix := status / 100
  185. if statusPrefix == 4 || statusPrefix == 5 {
  186. log.Log(skip, log.TRACE, "plainTextInternal (status=%d): %s", status, string(bs))
  187. }
  188. b.Resp.Header().Set("Content-Type", "text/plain;charset=utf-8")
  189. b.Resp.Header().Set("X-Content-Type-Options", "nosniff")
  190. b.Resp.WriteHeader(status)
  191. if _, err := b.Resp.Write(bs); err != nil {
  192. log.ErrorWithSkip(skip, "plainTextInternal (status=%d): write bytes failed: %v", status, err)
  193. }
  194. }
  195. // PlainTextBytes renders bytes as plain text
  196. func (b *Base) PlainTextBytes(status int, bs []byte) {
  197. b.plainTextInternal(2, status, bs)
  198. }
  199. // PlainText renders content as plain text
  200. func (b *Base) PlainText(status int, text string) {
  201. b.plainTextInternal(2, status, []byte(text))
  202. }
  203. // Redirect redirects the request
  204. func (b *Base) Redirect(location string, status ...int) {
  205. code := http.StatusSeeOther
  206. if len(status) == 1 {
  207. code = status[0]
  208. }
  209. if strings.Contains(location, "://") || strings.HasPrefix(location, "//") {
  210. // Some browsers (Safari) have buggy behavior for Cookie + Cache + External Redirection, eg: /my-path => https://other/path
  211. // 1. the first request to "/my-path" contains cookie
  212. // 2. some time later, the request to "/my-path" doesn't contain cookie (caused by Prevent web tracking)
  213. // 3. Gitea's Sessioner doesn't see the session cookie, so it generates a new session id, and returns it to browser
  214. // 4. then the browser accepts the empty session, then the user is logged out
  215. // So in this case, we should remove the session cookie from the response header
  216. removeSessionCookieHeader(b.Resp)
  217. }
  218. http.Redirect(b.Resp, b.Req, location, code)
  219. }
  220. type ServeHeaderOptions httplib.ServeHeaderOptions
  221. func (b *Base) SetServeHeaders(opt *ServeHeaderOptions) {
  222. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opt))
  223. }
  224. // ServeContent serves content to http request
  225. func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) {
  226. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opts))
  227. http.ServeContent(b.Resp, b.Req, opts.Filename, opts.LastModified, r)
  228. }
  229. // Close frees all resources hold by Context
  230. func (b *Base) cleanUp() {
  231. if b.Req != nil && b.Req.MultipartForm != nil {
  232. _ = b.Req.MultipartForm.RemoveAll() // remove the temp files buffered to tmp directory
  233. }
  234. }
  235. func (b *Base) Tr(msg string, args ...any) string {
  236. return b.Locale.Tr(msg, args...)
  237. }
  238. func (b *Base) TrN(cnt any, key1, keyN string, args ...any) string {
  239. return b.Locale.TrN(cnt, key1, keyN, args...)
  240. }
  241. func NewBaseContext(resp http.ResponseWriter, req *http.Request) (b *Base, closeFunc func()) {
  242. b = &Base{
  243. originCtx: req.Context(),
  244. Req: req,
  245. Resp: WrapResponseWriter(resp),
  246. Locale: middleware.Locale(resp, req),
  247. Data: middleware.GetContextData(req.Context()),
  248. }
  249. b.AppendContextValue(translation.ContextKey, b.Locale)
  250. b.Req = b.Req.WithContext(b)
  251. return b, b.cleanUp
  252. }