context.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 middleware
  5. import (
  6. "fmt"
  7. "html/template"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/Unknwon/macaron"
  13. "github.com/macaron-contrib/cache"
  14. "github.com/macaron-contrib/csrf"
  15. "github.com/macaron-contrib/i18n"
  16. "github.com/macaron-contrib/session"
  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/git"
  21. "github.com/gogits/gogs/modules/log"
  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. Repo struct {
  34. IsOwner bool
  35. IsTrueOwner bool
  36. IsWatching bool
  37. IsBranch bool
  38. IsTag bool
  39. IsCommit bool
  40. IsAdmin bool // Current user is admin level.
  41. HasAccess bool
  42. Repository *models.Repository
  43. Owner *models.User
  44. Commit *git.Commit
  45. Tag *git.Tag
  46. GitRepo *git.Repository
  47. BranchName string
  48. TagName string
  49. CommitId string
  50. RepoLink string
  51. CloneLink struct {
  52. SSH string
  53. HTTPS string
  54. Git string
  55. }
  56. CommitsCount int
  57. Mirror *models.Mirror
  58. }
  59. Org struct {
  60. IsOwner bool
  61. IsMember bool
  62. IsAdminTeam bool // In owner team or team that has admin permission level.
  63. Organization *models.User
  64. OrgLink string
  65. Team *models.Team
  66. }
  67. }
  68. // HasError returns true if error occurs in form validation.
  69. func (ctx *Context) HasApiError() bool {
  70. hasErr, ok := ctx.Data["HasError"]
  71. if !ok {
  72. return false
  73. }
  74. return hasErr.(bool)
  75. }
  76. func (ctx *Context) GetErrMsg() string {
  77. return ctx.Data["ErrorMsg"].(string)
  78. }
  79. // HasError returns true if error occurs in form validation.
  80. func (ctx *Context) HasError() bool {
  81. hasErr, ok := ctx.Data["HasError"]
  82. if !ok {
  83. return false
  84. }
  85. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  86. ctx.Data["Flash"] = ctx.Flash
  87. return hasErr.(bool)
  88. }
  89. // HTML calls Context.HTML and converts template name to string.
  90. func (ctx *Context) HTML(status int, name base.TplName) {
  91. ctx.Context.HTML(status, string(name))
  92. }
  93. // RenderWithErr used for page has form validation but need to prompt error to users.
  94. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  95. if form != nil {
  96. auth.AssignForm(form, ctx.Data)
  97. }
  98. ctx.Flash.ErrorMsg = msg
  99. ctx.Data["Flash"] = ctx.Flash
  100. ctx.HTML(200, tpl)
  101. }
  102. // Handle handles and logs error by given status.
  103. func (ctx *Context) Handle(status int, title string, err error) {
  104. if err != nil {
  105. log.Error(4, "%s: %v", title, err)
  106. if macaron.Env != macaron.PROD {
  107. ctx.Data["ErrorMsg"] = err
  108. }
  109. }
  110. switch status {
  111. case 404:
  112. ctx.Data["Title"] = "Page Not Found"
  113. case 500:
  114. ctx.Data["Title"] = "Internal Server Error"
  115. }
  116. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  117. }
  118. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  119. modtime := time.Now()
  120. for _, p := range params {
  121. switch v := p.(type) {
  122. case time.Time:
  123. modtime = v
  124. }
  125. }
  126. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  127. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  128. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  129. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  130. ctx.Resp.Header().Set("Expires", "0")
  131. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  132. ctx.Resp.Header().Set("Pragma", "public")
  133. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  134. }
  135. // Contexter initializes a classic context for a request.
  136. func Contexter() macaron.Handler {
  137. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  138. ctx := &Context{
  139. Context: c,
  140. Cache: cache,
  141. csrf: x,
  142. Flash: f,
  143. Session: sess,
  144. }
  145. // Compute current URL for real-time change language.
  146. link := setting.AppSubUrl + ctx.Req.RequestURI
  147. i := strings.Index(link, "?")
  148. if i > -1 {
  149. link = link[:i]
  150. }
  151. ctx.Data["Link"] = link
  152. ctx.Data["PageStartTime"] = time.Now()
  153. // Get user from session if logined.
  154. ctx.User = auth.SignedInUser(ctx.Req.Header, ctx.Session)
  155. if ctx.User != nil {
  156. ctx.IsSigned = true
  157. ctx.Data["IsSigned"] = ctx.IsSigned
  158. ctx.Data["SignedUser"] = ctx.User
  159. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  160. }
  161. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  162. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  163. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  164. ctx.Handle(500, "ParseMultipartForm", err)
  165. return
  166. }
  167. }
  168. ctx.Data["CsrfToken"] = x.GetToken()
  169. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  170. c.Map(ctx)
  171. }
  172. }