context.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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/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 *db.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. // HasError returns true if error occurs in form validation.
  82. func (c *Context) HasApiError() bool {
  83. hasErr, ok := c.Data["HasError"]
  84. if !ok {
  85. return false
  86. }
  87. return hasErr.(bool)
  88. }
  89. func (c *Context) GetErrMsg() string {
  90. return c.Data["ErrorMsg"].(string)
  91. }
  92. // HasError returns true if error occurs in form validation.
  93. func (c *Context) HasError() bool {
  94. hasErr, ok := c.Data["HasError"]
  95. if !ok {
  96. return false
  97. }
  98. c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
  99. c.Data["Flash"] = c.Flash
  100. return hasErr.(bool)
  101. }
  102. // HasValue returns true if value of given name exists.
  103. func (c *Context) HasValue(name string) bool {
  104. _, ok := c.Data[name]
  105. return ok
  106. }
  107. // HTML responses template with given status.
  108. func (c *Context) HTML(status int, name string) {
  109. log.Trace("Template: %s", name)
  110. c.Context.HTML(status, name)
  111. }
  112. // Success responses template with status http.StatusOK.
  113. func (c *Context) Success(name string) {
  114. c.HTML(http.StatusOK, name)
  115. }
  116. // JSONSuccess responses JSON with status http.StatusOK.
  117. func (c *Context) JSONSuccess(data interface{}) {
  118. c.JSON(http.StatusOK, data)
  119. }
  120. // RawRedirect simply calls underlying Redirect method with no escape.
  121. func (c *Context) RawRedirect(location string, status ...int) {
  122. c.Context.Redirect(location, status...)
  123. }
  124. // Redirect responses redirection with given location and status.
  125. // It escapes special characters in the location string.
  126. func (c *Context) Redirect(location string, status ...int) {
  127. c.Context.Redirect(template.EscapePound(location), status...)
  128. }
  129. // RedirectSubpath responses redirection with given location and status.
  130. // It prepends setting.Server.Subpath to the location string.
  131. func (c *Context) RedirectSubpath(location string, status ...int) {
  132. c.Redirect(conf.Server.Subpath+location, status...)
  133. }
  134. // RenderWithErr used for page has form validation but need to prompt error to users.
  135. func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
  136. if f != nil {
  137. form.Assign(f, c.Data)
  138. }
  139. c.Flash.ErrorMsg = msg
  140. c.Data["Flash"] = c.Flash
  141. c.HTML(http.StatusOK, tpl)
  142. }
  143. // NotFound renders the 404 page.
  144. func (c *Context) NotFound() {
  145. c.Title("status.page_not_found")
  146. c.HTML(http.StatusNotFound, fmt.Sprintf("status/%d", http.StatusNotFound))
  147. }
  148. // Error renders the 500 page.
  149. func (c *Context) Error(err error, msg string) {
  150. log.ErrorDepth(4, "%s: %v", msg, err)
  151. c.Title("status.internal_server_error")
  152. // Only in non-production mode or admin can see the actual error message.
  153. if !conf.IsProdMode() || (c.IsLogged && c.User.IsAdmin) {
  154. c.Data["ErrorMsg"] = err
  155. }
  156. c.HTML(http.StatusInternalServerError, fmt.Sprintf("status/%d", http.StatusInternalServerError))
  157. }
  158. // Errorf renders the 500 response with formatted message.
  159. func (c *Context) Errorf(err error, format string, args ...interface{}) {
  160. c.Error(err, fmt.Sprintf(format, args...))
  161. }
  162. // NotFoundOrError responses with 404 page for not found error and 500 page otherwise.
  163. func (c *Context) NotFoundOrError(err error, msg string) {
  164. if errutil.IsNotFound(err) {
  165. c.NotFound()
  166. return
  167. }
  168. c.Error(err, msg)
  169. }
  170. // NotFoundOrErrorf is same as NotFoundOrError but with formatted message.
  171. func (c *Context) NotFoundOrErrorf(err error, format string, args ...interface{}) {
  172. c.NotFoundOrError(err, fmt.Sprintf(format, args...))
  173. }
  174. func (c *Context) PlainText(status int, msg string) {
  175. c.Render.PlainText(status, []byte(msg))
  176. }
  177. func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  178. modtime := time.Now()
  179. for _, p := range params {
  180. switch v := p.(type) {
  181. case time.Time:
  182. modtime = v
  183. }
  184. }
  185. c.Resp.Header().Set("Content-Description", "File Transfer")
  186. c.Resp.Header().Set("Content-Type", "application/octet-stream")
  187. c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  188. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  189. c.Resp.Header().Set("Expires", "0")
  190. c.Resp.Header().Set("Cache-Control", "must-revalidate")
  191. c.Resp.Header().Set("Pragma", "public")
  192. http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
  193. }
  194. // Contexter initializes a classic context for a request.
  195. func Contexter() macaron.Handler {
  196. return func(ctx *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  197. c := &Context{
  198. Context: ctx,
  199. Cache: cache,
  200. csrf: x,
  201. Flash: f,
  202. Session: sess,
  203. Link: conf.Server.Subpath + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
  204. Repo: &Repository{
  205. PullRequest: &PullRequest{},
  206. },
  207. Org: &Organization{},
  208. }
  209. c.Data["Link"] = template.EscapePound(c.Link)
  210. c.Data["PageStartTime"] = time.Now()
  211. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  212. c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  213. c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
  214. c.Header().Set("Access-Control-Max-Age", "3600")
  215. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  216. }
  217. // Get user from session or header when possible
  218. c.User, c.IsBasicAuth, c.IsTokenAuth = auth.SignedInUser(c.Context, c.Session)
  219. if c.User != nil {
  220. c.IsLogged = true
  221. c.Data["IsLogged"] = c.IsLogged
  222. c.Data["LoggedUser"] = c.User
  223. c.Data["LoggedUserID"] = c.User.ID
  224. c.Data["LoggedUserName"] = c.User.Name
  225. c.Data["IsAdmin"] = c.User.IsAdmin
  226. } else {
  227. c.Data["LoggedUserID"] = 0
  228. c.Data["LoggedUserName"] = ""
  229. }
  230. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  231. if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
  232. if err := c.Req.ParseMultipartForm(conf.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  233. c.Error(err, "parse multipart form")
  234. return
  235. }
  236. }
  237. c.Data["CSRFToken"] = x.GetToken()
  238. c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  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. ctx.Map(c)
  248. }
  249. }