context.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. Team *models.Team
  67. }
  68. }
  69. // Query querys form parameter.
  70. func (ctx *Context) Query(name string) string {
  71. ctx.Req.ParseForm()
  72. return ctx.Req.Form.Get(name)
  73. }
  74. // HasError returns true if error occurs in form validation.
  75. func (ctx *Context) HasApiError() bool {
  76. hasErr, ok := ctx.Data["HasError"]
  77. if !ok {
  78. return false
  79. }
  80. return hasErr.(bool)
  81. }
  82. func (ctx *Context) GetErrMsg() string {
  83. return ctx.Data["ErrorMsg"].(string)
  84. }
  85. // HasError returns true if error occurs in form validation.
  86. func (ctx *Context) HasError() bool {
  87. hasErr, ok := ctx.Data["HasError"]
  88. if !ok {
  89. return false
  90. }
  91. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  92. ctx.Data["Flash"] = ctx.Flash
  93. return hasErr.(bool)
  94. }
  95. // HTML calls Context.HTML and converts template name to string.
  96. func (ctx *Context) HTML(status int, name base.TplName) {
  97. ctx.Context.HTML(status, string(name))
  98. }
  99. // RenderWithErr used for page has form validation but need to prompt error to users.
  100. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  101. if form != nil {
  102. auth.AssignForm(form, ctx.Data)
  103. }
  104. ctx.Flash.ErrorMsg = msg
  105. ctx.Data["Flash"] = ctx.Flash
  106. ctx.HTML(200, tpl)
  107. }
  108. // Handle handles and logs error by given status.
  109. func (ctx *Context) Handle(status int, title string, err error) {
  110. if err != nil {
  111. log.Error(4, "%s: %v", title, err)
  112. if macaron.Env != macaron.PROD {
  113. ctx.Data["ErrorMsg"] = err
  114. }
  115. }
  116. switch status {
  117. case 404:
  118. ctx.Data["Title"] = "Page Not Found"
  119. case 500:
  120. ctx.Data["Title"] = "Internal Server Error"
  121. }
  122. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  123. }
  124. func (ctx *Context) ServeFile(file string, names ...string) {
  125. var name string
  126. if len(names) > 0 {
  127. name = names[0]
  128. } else {
  129. name = path.Base(file)
  130. }
  131. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  132. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  133. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  134. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  135. ctx.Resp.Header().Set("Expires", "0")
  136. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  137. ctx.Resp.Header().Set("Pragma", "public")
  138. http.ServeFile(ctx.Resp, ctx.Req, file)
  139. }
  140. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  141. modtime := time.Now()
  142. for _, p := range params {
  143. switch v := p.(type) {
  144. case time.Time:
  145. modtime = v
  146. }
  147. }
  148. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  149. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  150. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  151. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  152. ctx.Resp.Header().Set("Expires", "0")
  153. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  154. ctx.Resp.Header().Set("Pragma", "public")
  155. http.ServeContent(ctx.Resp, ctx.Req, name, modtime, r)
  156. }
  157. // Contexter initializes a classic context for a request.
  158. func Contexter() macaron.Handler {
  159. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  160. ctx := &Context{
  161. Context: c,
  162. Locale: l,
  163. Cache: cache,
  164. csrf: x,
  165. Flash: f,
  166. Session: sess,
  167. }
  168. // Compute current URL for real-time change language.
  169. link := ctx.Req.RequestURI
  170. i := strings.Index(link, "?")
  171. if i > -1 {
  172. link = link[:i]
  173. }
  174. ctx.Data["Link"] = link
  175. ctx.Data["PageStartTime"] = time.Now()
  176. // Get user from session if logined.
  177. ctx.User = auth.SignedInUser(ctx.Req.Header, ctx.Session)
  178. if ctx.User != nil {
  179. ctx.IsSigned = true
  180. ctx.Data["IsSigned"] = ctx.IsSigned
  181. ctx.Data["SignedUser"] = ctx.User
  182. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  183. }
  184. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  185. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  186. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  187. ctx.Handle(500, "ParseMultipartForm", err)
  188. return
  189. }
  190. }
  191. ctx.Data["CsrfToken"] = x.GetToken()
  192. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  193. c.Map(ctx)
  194. }
  195. }