context.go 10 KB

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