context.go 5.7 KB

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