1
0

context.go 14 KB

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