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.

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