You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. "html/template"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/auth"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/go-macaron/cache"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/i18n"
  20. "github.com/go-macaron/session"
  21. macaron "gopkg.in/macaron.v1"
  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. User *models.User
  31. IsSigned bool
  32. IsBasicAuth bool
  33. Repo *Repository
  34. Org *Organization
  35. }
  36. // HasAPIError returns true if error occurs in form validation.
  37. func (ctx *Context) HasAPIError() bool {
  38. hasErr, ok := ctx.Data["HasError"]
  39. if !ok {
  40. return false
  41. }
  42. return hasErr.(bool)
  43. }
  44. // GetErrMsg returns error message
  45. func (ctx *Context) GetErrMsg() string {
  46. return ctx.Data["ErrorMsg"].(string)
  47. }
  48. // HasError returns true if error occurs in form validation.
  49. func (ctx *Context) HasError() bool {
  50. hasErr, ok := ctx.Data["HasError"]
  51. if !ok {
  52. return false
  53. }
  54. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  55. ctx.Data["Flash"] = ctx.Flash
  56. return hasErr.(bool)
  57. }
  58. // HasValue returns true if value of given name exists.
  59. func (ctx *Context) HasValue(name string) bool {
  60. _, ok := ctx.Data[name]
  61. return ok
  62. }
  63. // HTML calls Context.HTML and converts template name to string.
  64. func (ctx *Context) HTML(status int, name base.TplName) {
  65. log.Debug("Template: %s", name)
  66. ctx.Context.HTML(status, string(name))
  67. }
  68. // RenderWithErr used for page has form validation but need to prompt error to users.
  69. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  70. if form != nil {
  71. auth.AssignForm(form, ctx.Data)
  72. }
  73. ctx.Flash.ErrorMsg = msg
  74. ctx.Data["Flash"] = ctx.Flash
  75. ctx.HTML(200, tpl)
  76. }
  77. // Handle handles and logs error by given status.
  78. func (ctx *Context) Handle(status int, title string, err error) {
  79. if err != nil {
  80. log.Error(4, "%s: %v", title, err)
  81. if macaron.Env != macaron.PROD {
  82. ctx.Data["ErrorMsg"] = err
  83. }
  84. }
  85. switch status {
  86. case 404:
  87. ctx.Data["Title"] = "Page Not Found"
  88. case 500:
  89. ctx.Data["Title"] = "Internal Server Error"
  90. }
  91. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  92. }
  93. // NotFoundOrServerError use error check function to determine if the error
  94. // is about not found. It responses with 404 status code for not found error,
  95. // or error context description for logging purpose of 500 server error.
  96. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  97. if errck(err) {
  98. ctx.Handle(404, title, err)
  99. return
  100. }
  101. ctx.Handle(500, title, err)
  102. }
  103. // HandleText handles HTTP status code
  104. func (ctx *Context) HandleText(status int, title string) {
  105. if (status/100 == 4) || (status/100 == 5) {
  106. log.Error(4, "%s", title)
  107. }
  108. ctx.PlainText(status, []byte(title))
  109. }
  110. // ServeContent serves content to http request
  111. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  112. modtime := time.Now()
  113. for _, p := range params {
  114. switch v := p.(type) {
  115. case time.Time:
  116. modtime = v
  117. }
  118. }
  119. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  120. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  121. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  122. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  123. ctx.Resp.Header().Set("Expires", "0")
  124. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  125. ctx.Resp.Header().Set("Pragma", "public")
  126. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  127. }
  128. // Contexter initializes a classic context for a request.
  129. func Contexter() macaron.Handler {
  130. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  131. ctx := &Context{
  132. Context: c,
  133. Cache: cache,
  134. csrf: x,
  135. Flash: f,
  136. Session: sess,
  137. Repo: &Repository{
  138. PullRequest: &PullRequest{},
  139. },
  140. Org: &Organization{},
  141. }
  142. // Compute current URL for real-time change language.
  143. ctx.Data["Link"] = setting.AppSubURL + strings.TrimSuffix(ctx.Req.URL.Path, "/")
  144. ctx.Data["PageStartTime"] = time.Now()
  145. // Get user from session if logined.
  146. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  147. if ctx.User != nil {
  148. ctx.IsSigned = true
  149. ctx.Data["IsSigned"] = ctx.IsSigned
  150. ctx.Data["SignedUser"] = ctx.User
  151. ctx.Data["SignedUserID"] = ctx.User.ID
  152. ctx.Data["SignedUserName"] = ctx.User.Name
  153. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  154. } else {
  155. ctx.Data["SignedUserID"] = 0
  156. ctx.Data["SignedUserName"] = ""
  157. }
  158. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  159. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  160. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  161. ctx.Handle(500, "ParseMultipartForm", err)
  162. return
  163. }
  164. }
  165. ctx.Data["CsrfToken"] = x.GetToken()
  166. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  167. log.Debug("Session ID: %s", sess.ID())
  168. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  169. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  170. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  171. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  172. c.Map(ctx)
  173. }
  174. }