context.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "path"
  11. "strings"
  12. "time"
  13. "github.com/Unknwon/macaron"
  14. "github.com/macaron-contrib/cache"
  15. "github.com/macaron-contrib/csrf"
  16. "github.com/macaron-contrib/i18n"
  17. "github.com/macaron-contrib/session"
  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/git"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. // Context represents context of a request.
  26. type Context struct {
  27. *macaron.Context
  28. i18n.Locale
  29. Cache cache.Cache
  30. csrf csrf.CSRF
  31. Flash *session.Flash
  32. Session session.Store
  33. User *models.User
  34. IsSigned bool
  35. Repo struct {
  36. IsOwner bool
  37. IsTrueOwner bool
  38. IsWatching bool
  39. IsBranch bool
  40. IsTag bool
  41. IsCommit bool
  42. HasAccess bool
  43. Repository *models.Repository
  44. Owner *models.User
  45. Commit *git.Commit
  46. Tag *git.Tag
  47. GitRepo *git.Repository
  48. BranchName string
  49. TagName string
  50. CommitId string
  51. RepoLink string
  52. CloneLink struct {
  53. SSH string
  54. HTTPS string
  55. Git string
  56. }
  57. CommitsCount int
  58. Mirror *models.Mirror
  59. }
  60. Org struct {
  61. IsOwner bool
  62. IsMember bool
  63. IsAdminTeam bool // In owner team or team that has admin permission level.
  64. Organization *models.User
  65. OrgLink string
  66. }
  67. }
  68. // Query querys form parameter.
  69. func (ctx *Context) Query(name string) string {
  70. ctx.Req.ParseForm()
  71. return ctx.Req.Form.Get(name)
  72. }
  73. // HasError returns true if error occurs in form validation.
  74. func (ctx *Context) HasApiError() bool {
  75. hasErr, ok := ctx.Data["HasError"]
  76. if !ok {
  77. return false
  78. }
  79. return hasErr.(bool)
  80. }
  81. func (ctx *Context) GetErrMsg() string {
  82. return ctx.Data["ErrorMsg"].(string)
  83. }
  84. // HasError returns true if error occurs in form validation.
  85. func (ctx *Context) HasError() bool {
  86. hasErr, ok := ctx.Data["HasError"]
  87. if !ok {
  88. return false
  89. }
  90. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  91. ctx.Data["Flash"] = ctx.Flash
  92. return hasErr.(bool)
  93. }
  94. // HTML calls Context.HTML and converts template name to string.
  95. func (ctx *Context) HTML(status int, name base.TplName) {
  96. ctx.Context.HTML(status, string(name))
  97. }
  98. // RenderWithErr used for page has form validation but need to prompt error to users.
  99. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  100. if form != nil {
  101. auth.AssignForm(form, ctx.Data)
  102. }
  103. ctx.Flash.ErrorMsg = msg
  104. ctx.Data["Flash"] = ctx.Flash
  105. ctx.HTML(200, tpl)
  106. }
  107. // Handle handles and logs error by given status.
  108. func (ctx *Context) Handle(status int, title string, err error) {
  109. if err != nil {
  110. log.Error(4, "%s: %v", title, err)
  111. if macaron.Env != macaron.PROD {
  112. ctx.Data["ErrorMsg"] = err
  113. }
  114. }
  115. switch status {
  116. case 404:
  117. ctx.Data["Title"] = "Page Not Found"
  118. case 500:
  119. ctx.Data["Title"] = "Internal Server Error"
  120. }
  121. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  122. }
  123. func (ctx *Context) ServeFile(file string, names ...string) {
  124. var name string
  125. if len(names) > 0 {
  126. name = names[0]
  127. } else {
  128. name = path.Base(file)
  129. }
  130. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  131. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  132. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  133. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  134. ctx.Resp.Header().Set("Expires", "0")
  135. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  136. ctx.Resp.Header().Set("Pragma", "public")
  137. http.ServeFile(ctx.Resp, ctx.Req, file)
  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, 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. Locale: l,
  162. Cache: cache,
  163. csrf: x,
  164. Flash: f,
  165. Session: sess,
  166. }
  167. // Compute current URL for real-time change language.
  168. link := ctx.Req.RequestURI
  169. i := strings.Index(link, "?")
  170. if i > -1 {
  171. link = link[:i]
  172. }
  173. ctx.Data["Link"] = link
  174. ctx.Data["PageStartTime"] = time.Now()
  175. // Get user from session if logined.
  176. ctx.User = auth.SignedInUser(ctx.Req.Header, ctx.Session)
  177. if ctx.User != nil {
  178. ctx.IsSigned = true
  179. ctx.Data["IsSigned"] = ctx.IsSigned
  180. ctx.Data["SignedUser"] = ctx.User
  181. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  182. }
  183. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  184. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  185. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  186. ctx.Handle(500, "ParseMultipartForm", err)
  187. return
  188. }
  189. }
  190. ctx.Data["CsrfToken"] = x.GetToken()
  191. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  192. c.Map(ctx)
  193. }
  194. }