context.go 8.7 KB

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