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