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