You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 6.0 kB

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