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 5.3 kB

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