context.go 8.9 KB

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