context.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. log "gopkg.in/clog.v1"
  17. "gopkg.in/macaron.v1"
  18. "github.com/gogits/gogs/models"
  19. "github.com/gogits/gogs/modules/auth"
  20. "github.com/gogits/gogs/modules/base"
  21. "github.com/gogits/gogs/modules/form"
  22. "github.com/gogits/gogs/modules/setting"
  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. User *models.User
  32. IsSigned bool
  33. IsBasicAuth bool
  34. Repo *Repository
  35. Org *Organization
  36. }
  37. // HasError returns true if error occurs in form validation.
  38. func (ctx *Context) HasApiError() bool {
  39. hasErr, ok := ctx.Data["HasError"]
  40. if !ok {
  41. return false
  42. }
  43. return hasErr.(bool)
  44. }
  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.Trace("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, f interface{}) {
  70. if f != nil {
  71. form.Assign(f, 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. switch status {
  80. case 404:
  81. ctx.Data["Title"] = "Page Not Found"
  82. case 500:
  83. ctx.Data["Title"] = "Internal Server Error"
  84. log.Error(2, "%s: %v", title, err)
  85. if !setting.ProdMode || (ctx.IsSigned && ctx.User.IsAdmin) {
  86. ctx.Data["ErrorMsg"] = err
  87. }
  88. }
  89. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  90. }
  91. // NotFound simply renders the 404 page.
  92. func (ctx *Context) NotFound() {
  93. ctx.Handle(404, "", nil)
  94. }
  95. // NotFoundOrServerError use error check function to determine if the error
  96. // is about not found. It responses with 404 status code for not found error,
  97. // or error context description for logging purpose of 500 server error.
  98. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  99. if errck(err) {
  100. ctx.NotFound()
  101. return
  102. }
  103. ctx.Handle(500, title, err)
  104. }
  105. func (ctx *Context) HandleText(status int, title string) {
  106. ctx.PlainText(status, []byte(title))
  107. }
  108. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  109. modtime := time.Now()
  110. for _, p := range params {
  111. switch v := p.(type) {
  112. case time.Time:
  113. modtime = v
  114. }
  115. }
  116. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  117. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  118. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  119. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  120. ctx.Resp.Header().Set("Expires", "0")
  121. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  122. ctx.Resp.Header().Set("Pragma", "public")
  123. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  124. }
  125. // Contexter initializes a classic context for a request.
  126. func Contexter() macaron.Handler {
  127. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  128. ctx := &Context{
  129. Context: c,
  130. Cache: cache,
  131. csrf: x,
  132. Flash: f,
  133. Session: sess,
  134. Repo: &Repository{
  135. PullRequest: &PullRequest{},
  136. },
  137. Org: &Organization{},
  138. }
  139. if len(setting.HTTP.AccessControlAllowOrigin) > 0 {
  140. ctx.Header().Set("Access-Control-Allow-Origin", setting.HTTP.AccessControlAllowOrigin)
  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.Trace("Session ID: %s", sess.ID())
  168. log.Trace("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. }