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