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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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.WrittenStatus() != 0
  81. }
  82. func (b *Base) WrittenStatus() int {
  83. return b.Resp.WrittenStatus()
  84. }
  85. // Status writes status code
  86. func (b *Base) Status(status int) {
  87. b.Resp.WriteHeader(status)
  88. }
  89. // Write writes data to web browser
  90. func (b *Base) Write(bs []byte) (int, error) {
  91. return b.Resp.Write(bs)
  92. }
  93. // RespHeader returns the response header
  94. func (b *Base) RespHeader() http.Header {
  95. return b.Resp.Header()
  96. }
  97. // Error returned an error to web browser
  98. func (b *Base) Error(status int, contents ...string) {
  99. v := http.StatusText(status)
  100. if len(contents) > 0 {
  101. v = contents[0]
  102. }
  103. http.Error(b.Resp, v, status)
  104. }
  105. // JSON render content as JSON
  106. func (b *Base) JSON(status int, content any) {
  107. b.Resp.Header().Set("Content-Type", "application/json;charset=utf-8")
  108. b.Resp.WriteHeader(status)
  109. if err := json.NewEncoder(b.Resp).Encode(content); err != nil {
  110. log.Error("Render JSON failed: %v", err)
  111. }
  112. }
  113. // RemoteAddr returns the client machine ip address
  114. func (b *Base) RemoteAddr() string {
  115. return b.Req.RemoteAddr
  116. }
  117. // Params returns the param on route
  118. func (b *Base) Params(p string) string {
  119. s, _ := url.PathUnescape(chi.URLParam(b.Req, strings.TrimPrefix(p, ":")))
  120. return s
  121. }
  122. func (b *Base) PathParamRaw(p string) string {
  123. return chi.URLParam(b.Req, strings.TrimPrefix(p, ":"))
  124. }
  125. // ParamsInt64 returns the param on route as int64
  126. func (b *Base) ParamsInt64(p string) int64 {
  127. v, _ := strconv.ParseInt(b.Params(p), 10, 64)
  128. return v
  129. }
  130. // SetParams set params into routes
  131. func (b *Base) SetParams(k, v string) {
  132. chiCtx := chi.RouteContext(b)
  133. chiCtx.URLParams.Add(strings.TrimPrefix(k, ":"), url.PathEscape(v))
  134. }
  135. // FormString returns the first value matching the provided key in the form as a string
  136. func (b *Base) FormString(key string) string {
  137. return b.Req.FormValue(key)
  138. }
  139. // FormStrings returns a string slice for the provided key from the form
  140. func (b *Base) FormStrings(key string) []string {
  141. if b.Req.Form == nil {
  142. if err := b.Req.ParseMultipartForm(32 << 20); err != nil {
  143. return nil
  144. }
  145. }
  146. if v, ok := b.Req.Form[key]; ok {
  147. return v
  148. }
  149. return nil
  150. }
  151. // FormTrim returns the first value for the provided key in the form as a space trimmed string
  152. func (b *Base) FormTrim(key string) string {
  153. return strings.TrimSpace(b.Req.FormValue(key))
  154. }
  155. // FormInt returns the first value for the provided key in the form as an int
  156. func (b *Base) FormInt(key string) int {
  157. v, _ := strconv.Atoi(b.Req.FormValue(key))
  158. return v
  159. }
  160. // FormInt64 returns the first value for the provided key in the form as an int64
  161. func (b *Base) FormInt64(key string) int64 {
  162. v, _ := strconv.ParseInt(b.Req.FormValue(key), 10, 64)
  163. return v
  164. }
  165. // FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
  166. func (b *Base) FormBool(key string) bool {
  167. s := b.Req.FormValue(key)
  168. v, _ := strconv.ParseBool(s)
  169. v = v || strings.EqualFold(s, "on")
  170. return v
  171. }
  172. // FormOptionalBool returns an OptionalBoolTrue or OptionalBoolFalse if the value
  173. // for the provided key exists in the form else it returns OptionalBoolNone
  174. func (b *Base) FormOptionalBool(key string) util.OptionalBool {
  175. value := b.Req.FormValue(key)
  176. if len(value) == 0 {
  177. return util.OptionalBoolNone
  178. }
  179. s := b.Req.FormValue(key)
  180. v, _ := strconv.ParseBool(s)
  181. v = v || strings.EqualFold(s, "on")
  182. return util.OptionalBoolOf(v)
  183. }
  184. func (b *Base) SetFormString(key, value string) {
  185. _ = b.Req.FormValue(key) // force parse form
  186. b.Req.Form.Set(key, value)
  187. }
  188. // PlainTextBytes renders bytes as plain text
  189. func (b *Base) plainTextInternal(skip, status int, bs []byte) {
  190. statusPrefix := status / 100
  191. if statusPrefix == 4 || statusPrefix == 5 {
  192. log.Log(skip, log.TRACE, "plainTextInternal (status=%d): %s", status, string(bs))
  193. }
  194. b.Resp.Header().Set("Content-Type", "text/plain;charset=utf-8")
  195. b.Resp.Header().Set("X-Content-Type-Options", "nosniff")
  196. b.Resp.WriteHeader(status)
  197. if _, err := b.Resp.Write(bs); err != nil {
  198. log.ErrorWithSkip(skip, "plainTextInternal (status=%d): write bytes failed: %v", status, err)
  199. }
  200. }
  201. // PlainTextBytes renders bytes as plain text
  202. func (b *Base) PlainTextBytes(status int, bs []byte) {
  203. b.plainTextInternal(2, status, bs)
  204. }
  205. // PlainText renders content as plain text
  206. func (b *Base) PlainText(status int, text string) {
  207. b.plainTextInternal(2, status, []byte(text))
  208. }
  209. // Redirect redirects the request
  210. func (b *Base) Redirect(location string, status ...int) {
  211. code := http.StatusSeeOther
  212. if len(status) == 1 {
  213. code = status[0]
  214. }
  215. if strings.Contains(location, "://") || strings.HasPrefix(location, "//") {
  216. // Some browsers (Safari) have buggy behavior for Cookie + Cache + External Redirection, eg: /my-path => https://other/path
  217. // 1. the first request to "/my-path" contains cookie
  218. // 2. some time later, the request to "/my-path" doesn't contain cookie (caused by Prevent web tracking)
  219. // 3. Gitea's Sessioner doesn't see the session cookie, so it generates a new session id, and returns it to browser
  220. // 4. then the browser accepts the empty session, then the user is logged out
  221. // So in this case, we should remove the session cookie from the response header
  222. removeSessionCookieHeader(b.Resp)
  223. }
  224. http.Redirect(b.Resp, b.Req, location, code)
  225. }
  226. type ServeHeaderOptions httplib.ServeHeaderOptions
  227. func (b *Base) SetServeHeaders(opt *ServeHeaderOptions) {
  228. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opt))
  229. }
  230. // ServeContent serves content to http request
  231. func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) {
  232. httplib.ServeSetHeaders(b.Resp, (*httplib.ServeHeaderOptions)(opts))
  233. http.ServeContent(b.Resp, b.Req, opts.Filename, opts.LastModified, r)
  234. }
  235. // Close frees all resources hold by Context
  236. func (b *Base) cleanUp() {
  237. if b.Req != nil && b.Req.MultipartForm != nil {
  238. _ = b.Req.MultipartForm.RemoveAll() // remove the temp files buffered to tmp directory
  239. }
  240. }
  241. func (b *Base) Tr(msg string, args ...any) string {
  242. return b.Locale.Tr(msg, args...)
  243. }
  244. func (b *Base) TrN(cnt any, key1, keyN string, args ...any) string {
  245. return b.Locale.TrN(cnt, key1, keyN, args...)
  246. }
  247. func NewBaseContext(resp http.ResponseWriter, req *http.Request) (b *Base, closeFunc func()) {
  248. b = &Base{
  249. originCtx: req.Context(),
  250. Req: req,
  251. Resp: WrapResponseWriter(resp),
  252. Locale: middleware.Locale(resp, req),
  253. Data: middleware.GetContextData(req.Context()),
  254. }
  255. b.AppendContextValue(translation.ContextKey, b.Locale)
  256. b.Req = b.Req.WithContext(b)
  257. return b, b.cleanUp
  258. }