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 9.3KB

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