context.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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) HandleText(status int, title string) {
  123. if (status / 100 == 4) || (status / 100 == 5) {
  124. log.Error(4, "%s", title)
  125. }
  126. ctx.RenderData(status, []byte(title))
  127. }
  128. func (ctx *Context) HandleAPI(status int, obj interface{}) {
  129. var message string
  130. if err, ok := obj.(error); ok {
  131. message = err.Error()
  132. } else {
  133. message = obj.(string)
  134. }
  135. ctx.JSON(status, map[string]string{
  136. "message": message,
  137. })
  138. }
  139. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  140. modtime := time.Now()
  141. for _, p := range params {
  142. switch v := p.(type) {
  143. case time.Time:
  144. modtime = v
  145. }
  146. }
  147. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  148. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  149. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  150. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  151. ctx.Resp.Header().Set("Expires", "0")
  152. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  153. ctx.Resp.Header().Set("Pragma", "public")
  154. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  155. }
  156. // Contexter initializes a classic context for a request.
  157. func Contexter() macaron.Handler {
  158. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  159. ctx := &Context{
  160. Context: c,
  161. Cache: cache,
  162. csrf: x,
  163. Flash: f,
  164. Session: sess,
  165. }
  166. // Compute current URL for real-time change language.
  167. ctx.Data["Link"] = setting.AppSubUrl + ctx.Req.URL.Path
  168. ctx.Data["PageStartTime"] = time.Now()
  169. // Get user from session if logined.
  170. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Req.Request, ctx.Session)
  171. if ctx.User != nil {
  172. ctx.IsSigned = true
  173. ctx.Data["IsSigned"] = ctx.IsSigned
  174. ctx.Data["SignedUser"] = ctx.User
  175. ctx.Data["SignedUserName"] = ctx.User.Name
  176. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  177. } else {
  178. ctx.Data["SignedUserName"] = ""
  179. }
  180. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  181. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  182. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  183. ctx.Handle(500, "ParseMultipartForm", err)
  184. return
  185. }
  186. }
  187. ctx.Data["CsrfToken"] = x.GetToken()
  188. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  189. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  190. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  191. c.Map(ctx)
  192. }
  193. }