1
0

context.go 8.5 KB

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