1
0

context.go 11 KB

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