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.

186 lines
5.2 KiB

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