1
0

context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package context
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/flamego/cache"
  10. "github.com/flamego/csrf"
  11. "github.com/flamego/flamego"
  12. "github.com/flamego/i18n"
  13. "github.com/flamego/session"
  14. "github.com/flamego/template"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/database"
  18. "gogs.io/gogs/internal/errutil"
  19. "gogs.io/gogs/internal/form"
  20. "gogs.io/gogs/internal/lazyregexp"
  21. gogstemplate "gogs.io/gogs/internal/template"
  22. )
  23. // Resp is a wrapper for ResponseWriter to provide compatibility.
  24. type Resp struct {
  25. http.ResponseWriter
  26. }
  27. // Write writes data to the response.
  28. func (r *Resp) Write(data []byte) (int, error) {
  29. return r.ResponseWriter.Write(data)
  30. }
  31. // Req is a wrapper for http.Request to provide compatibility.
  32. type Req struct {
  33. *http.Request
  34. }
  35. // Context represents context of a request.
  36. type Context struct {
  37. flamego.Context
  38. template.Template
  39. i18n.Locale
  40. Cache cache.Cache
  41. csrf csrf.CSRF
  42. Flash *FlashData
  43. Session session.Session
  44. Resp *Resp
  45. Req *Req
  46. ResponseWriter http.ResponseWriter
  47. Request *http.Request
  48. Data template.Data
  49. Link string // Current request URL
  50. User *database.User
  51. IsLogged bool
  52. IsBasicAuth bool
  53. IsTokenAuth bool
  54. Repo *Repository
  55. Org *Organization
  56. }
  57. // FlashData represents flash data structure.
  58. type FlashData struct {
  59. ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
  60. }
  61. // Error sets error message.
  62. func (f *FlashData) Error(msg string) {
  63. f.ErrorMsg = msg
  64. }
  65. // Success sets success message.
  66. func (f *FlashData) Success(msg string) {
  67. f.SuccessMsg = msg
  68. }
  69. // Info sets info message.
  70. func (f *FlashData) Info(msg string) {
  71. f.InfoMsg = msg
  72. }
  73. // Warning sets warning message.
  74. func (f *FlashData) Warning(msg string) {
  75. f.WarningMsg = msg
  76. }
  77. // RawTitle sets the "Title" field in template data.
  78. func (c *Context) RawTitle(title string) {
  79. c.Data["Title"] = title
  80. }
  81. // Tr is a wrapper for i18n.Locale.Translate.
  82. func (c *Context) Tr(key string, args ...any) string {
  83. return c.Locale.Translate(key, args...)
  84. }
  85. // Title localizes the "Title" field in template data.
  86. func (c *Context) Title(locale string) {
  87. c.RawTitle(c.Tr(locale))
  88. }
  89. // PageIs sets "PageIsxxx" field in template data.
  90. func (c *Context) PageIs(name string) {
  91. c.Data["PageIs"+name] = true
  92. }
  93. // Require sets "Requirexxx" field in template data.
  94. func (c *Context) Require(name string) {
  95. c.Data["Require"+name] = true
  96. }
  97. func (c *Context) RequireHighlightJS() {
  98. c.Require("HighlightJS")
  99. }
  100. func (c *Context) RequireSimpleMDE() {
  101. c.Require("SimpleMDE")
  102. }
  103. func (c *Context) RequireAutosize() {
  104. c.Require("Autosize")
  105. }
  106. func (c *Context) RequireDropzone() {
  107. c.Require("Dropzone")
  108. }
  109. // FormErr sets "Err_xxx" field in template data.
  110. func (c *Context) FormErr(names ...string) {
  111. for i := range names {
  112. c.Data["Err_"+names[i]] = true
  113. }
  114. }
  115. // UserID returns ID of current logged in user.
  116. // It returns 0 if visitor is anonymous.
  117. func (c *Context) UserID() int64 {
  118. if !c.IsLogged {
  119. return 0
  120. }
  121. return c.User.ID
  122. }
  123. func (c *Context) GetErrMsg() string {
  124. return c.Data["ErrorMsg"].(string)
  125. }
  126. // HasError returns true if error occurs in form validation.
  127. func (c *Context) HasError() bool {
  128. hasErr, ok := c.Data["HasError"]
  129. if !ok {
  130. return false
  131. }
  132. c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
  133. c.Data["Flash"] = c.Flash
  134. return hasErr.(bool)
  135. }
  136. // HasValue returns true if value of given name exists.
  137. func (c *Context) HasValue(name string) bool {
  138. _, ok := c.Data[name]
  139. return ok
  140. }
  141. // Status sets the HTTP status code.
  142. func (c *Context) Status(status int) {
  143. c.ResponseWriter.WriteHeader(status)
  144. }
  145. // JSON renders JSON response with given status and data.
  146. func (c *Context) JSON(status int, data any) {
  147. c.ResponseWriter.Header().Set("Content-Type", "application/json")
  148. c.ResponseWriter.WriteHeader(status)
  149. json.NewEncoder(c.ResponseWriter).Encode(data)
  150. }
  151. // Header returns the response header map.
  152. func (c *Context) Header() http.Header {
  153. return c.ResponseWriter.Header()
  154. }
  155. // Written returns whether the response has been written.
  156. func (c *Context) Written() bool {
  157. // In Flamego, we need to track this ourselves or check the response writer
  158. // For now, we'll assume if status code is set, it's written
  159. // This is a simplification - in production, you'd want a proper wrapper
  160. return false // TODO: Implement proper tracking
  161. }
  162. // Write writes data to the response.
  163. func (c *Context) Write(data []byte) (int, error) {
  164. return c.ResponseWriter.Write(data)
  165. }
  166. // ParamsInt64 returns value of the given bind parameter parsed as int64.
  167. func (c *Context) ParamsInt64(name string) int64 {
  168. return c.Context.ParamInt64(name)
  169. }
  170. // Language returns the language tag from the current locale.
  171. func (c *Context) Language() string {
  172. // Flamego's i18n.Locale doesn't have a Language() method
  173. // We need to use a different approach or store the language
  174. // For now, return empty string as a placeholder
  175. return "" // TODO: Implement proper language tracking
  176. }
  177. // SetCookie sets a cookie.
  178. func (c *Context) SetCookie(name, value string, maxAge int, path string) {
  179. http.SetCookie(c.ResponseWriter, &http.Cookie{
  180. Name: name,
  181. Value: value,
  182. MaxAge: maxAge,
  183. Path: path,
  184. HttpOnly: true,
  185. })
  186. }
  187. // GetCookie gets a cookie value.
  188. func (c *Context) GetCookie(name string) string {
  189. cookie, err := c.Request.Cookie(name)
  190. if err != nil {
  191. return ""
  192. }
  193. return cookie.Value
  194. }
  195. // HTML responses template with given status.
  196. func (c *Context) HTML(status int, name string) {
  197. log.Trace("Template: %s", name)
  198. c.ResponseWriter.WriteHeader(status)
  199. c.Template.HTML(status, name)
  200. }
  201. // Success responses template with status http.StatusOK.
  202. func (c *Context) Success(name string) {
  203. c.HTML(http.StatusOK, name)
  204. }
  205. // JSONSuccess responses JSON with status http.StatusOK.
  206. func (c *Context) JSONSuccess(data any) {
  207. c.JSON(http.StatusOK, data)
  208. }
  209. // RawRedirect simply calls underlying Redirect method with no escape.
  210. func (c *Context) RawRedirect(location string, status ...int) {
  211. code := http.StatusFound
  212. if len(status) > 0 {
  213. code = status[0]
  214. }
  215. http.Redirect(c.ResponseWriter, c.Request, location, code)
  216. }
  217. // Redirect responses redirection with given location and status.
  218. // It escapes special characters in the location string.
  219. func (c *Context) Redirect(location string, status ...int) {
  220. c.RawRedirect(gogstemplate.EscapePound(location), status...)
  221. }
  222. // RedirectSubpath responses redirection with given location and status.
  223. // It prepends setting.Server.Subpath to the location string.
  224. func (c *Context) RedirectSubpath(location string, status ...int) {
  225. c.Redirect(conf.Server.Subpath+location, status...)
  226. }
  227. // RenderWithErr used for page has form validation but need to prompt error to users.
  228. func (c *Context) RenderWithErr(msg, tpl string, f any) {
  229. if f != nil {
  230. form.Assign(f, c.Data)
  231. }
  232. c.Flash.ErrorMsg = msg
  233. c.Data["Flash"] = c.Flash
  234. c.HTML(http.StatusOK, tpl)
  235. }
  236. // NotFound renders the 404 page.
  237. func (c *Context) NotFound() {
  238. c.Title("status.page_not_found")
  239. c.HTML(http.StatusNotFound, fmt.Sprintf("status/%d", http.StatusNotFound))
  240. }
  241. // Error renders the 500 page.
  242. func (c *Context) Error(err error, msg string) {
  243. log.ErrorDepth(4, "%s: %v", msg, err)
  244. c.Title("status.internal_server_error")
  245. // Only in non-production mode or admin can see the actual error message.
  246. if !conf.IsProdMode() || (c.IsLogged && c.User.IsAdmin) {
  247. c.Data["ErrorMsg"] = err
  248. }
  249. c.HTML(http.StatusInternalServerError, fmt.Sprintf("status/%d", http.StatusInternalServerError))
  250. }
  251. // Errorf renders the 500 response with formatted message.
  252. func (c *Context) Errorf(err error, format string, args ...any) {
  253. c.Error(err, fmt.Sprintf(format, args...))
  254. }
  255. // NotFoundOrError responses with 404 page for not found error and 500 page otherwise.
  256. func (c *Context) NotFoundOrError(err error, msg string) {
  257. if errutil.IsNotFound(err) {
  258. c.NotFound()
  259. return
  260. }
  261. c.Error(err, msg)
  262. }
  263. // NotFoundOrErrorf is same as NotFoundOrError but with formatted message.
  264. func (c *Context) NotFoundOrErrorf(err error, format string, args ...any) {
  265. c.NotFoundOrError(err, fmt.Sprintf(format, args...))
  266. }
  267. func (c *Context) PlainText(status int, msg string) {
  268. c.ResponseWriter.Header().Set("Content-Type", "text/plain; charset=utf-8")
  269. c.ResponseWriter.WriteHeader(status)
  270. c.ResponseWriter.Write([]byte(msg))
  271. }
  272. func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...any) {
  273. modtime := time.Now()
  274. for _, p := range params {
  275. switch v := p.(type) {
  276. case time.Time:
  277. modtime = v
  278. }
  279. }
  280. c.ResponseWriter.Header().Set("Content-Description", "File Transfer")
  281. c.ResponseWriter.Header().Set("Content-Type", "application/octet-stream")
  282. c.ResponseWriter.Header().Set("Content-Disposition", "attachment; filename="+name)
  283. c.ResponseWriter.Header().Set("Content-Transfer-Encoding", "binary")
  284. c.ResponseWriter.Header().Set("Expires", "0")
  285. c.ResponseWriter.Header().Set("Cache-Control", "must-revalidate")
  286. c.ResponseWriter.Header().Set("Pragma", "public")
  287. http.ServeContent(c.ResponseWriter, c.Request, name, modtime, r)
  288. }
  289. // csrfTokenExcludePattern matches characters that are not used for generating
  290. // CSRF tokens, see all possible characters at
  291. // https://github.com/go-macaron/csrf/blob/5d38f39de352972063d1ef026fc477283841bb9b/csrf.go#L148.
  292. var csrfTokenExcludePattern = lazyregexp.New(`[^a-zA-Z0-9-_].*`)
  293. // Contexter initializes a classic context for a request.
  294. func Contexter(store Store) flamego.Handler {
  295. return func(fctx flamego.Context, tpl template.Template, l i18n.Locale, cache cache.Cache, sess session.Session, x csrf.CSRF, w http.ResponseWriter, req *http.Request) {
  296. // Get or create flash data from session
  297. flash := &FlashData{}
  298. if val := sess.Get("flamego::session::flash"); val != nil {
  299. if f, ok := val.(*FlashData); ok {
  300. flash = f
  301. }
  302. }
  303. c := &Context{
  304. Context: fctx,
  305. Template: tpl,
  306. Locale: l,
  307. Cache: cache,
  308. csrf: x,
  309. Flash: flash,
  310. Session: sess,
  311. Resp: &Resp{w},
  312. Req: &Req{req},
  313. ResponseWriter: w,
  314. Request: req,
  315. Data: make(template.Data),
  316. Link: conf.Server.Subpath + strings.TrimSuffix(req.URL.Path, "/"),
  317. Repo: &Repository{
  318. PullRequest: &PullRequest{},
  319. },
  320. Org: &Organization{},
  321. }
  322. c.Data["Link"] = gogstemplate.EscapePound(c.Link)
  323. c.Data["PageStartTime"] = time.Now()
  324. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  325. w.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  326. w.Header().Set("Access-Control-Allow-Credentials", "true")
  327. w.Header().Set("Access-Control-Max-Age", "3600")
  328. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  329. }
  330. // Get user from session or header when possible
  331. c.User, c.IsBasicAuth, c.IsTokenAuth = authenticatedUser(store, fctx, sess)
  332. if c.User != nil {
  333. c.IsLogged = true
  334. c.Data["IsLogged"] = c.IsLogged
  335. c.Data["LoggedUser"] = c.User
  336. c.Data["LoggedUserID"] = c.User.ID
  337. c.Data["LoggedUserName"] = c.User.Name
  338. c.Data["IsAdmin"] = c.User.IsAdmin
  339. } else {
  340. c.Data["LoggedUserID"] = 0
  341. c.Data["LoggedUserName"] = ""
  342. }
  343. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  344. if req.Method == "POST" && strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") {
  345. if err := req.ParseMultipartForm(conf.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  346. c.Error(err, "parse multipart form")
  347. return
  348. }
  349. }
  350. // 🚨 SECURITY: Prevent XSS from injected CSRF cookie by stripping all
  351. // characters that are not used for generating CSRF tokens, see
  352. // https://github.com/gogs/gogs/issues/6953 for details.
  353. csrfToken := csrfTokenExcludePattern.ReplaceAllString(x.Token(), "")
  354. c.Data["CSRFToken"] = csrfToken
  355. c.Data["CSRFTokenHTML"] = gogstemplate.Safe(`<input type="hidden" name="_csrf" value="` + csrfToken + `">`)
  356. log.Trace("Session ID: %s", sess.ID())
  357. log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
  358. c.Data["ShowRegistrationButton"] = !conf.Auth.DisableRegistration
  359. c.Data["ShowFooterBranding"] = conf.Other.ShowFooterBranding
  360. c.renderNoticeBanner()
  361. // 🚨 SECURITY: Prevent MIME type sniffing in some browsers,
  362. // see https://github.com/gogs/gogs/issues/5397 for details.
  363. w.Header().Set("X-Content-Type-Options", "nosniff")
  364. w.Header().Set("X-Frame-Options", "deny")
  365. fctx.MapTo(c, (*Context)(nil))
  366. }
  367. }