context.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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/go-macaron/cache"
  13. "github.com/go-macaron/csrf"
  14. "github.com/go-macaron/i18n"
  15. "github.com/go-macaron/session"
  16. "gopkg.in/macaron.v1"
  17. "github.com/gogits/git-shell"
  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/log"
  22. "github.com/gogits/gogs/modules/setting"
  23. )
  24. type RepoContext struct {
  25. AccessMode models.AccessMode
  26. IsWatching bool
  27. IsViewBranch bool
  28. IsViewTag bool
  29. IsViewCommit bool
  30. Repository *models.Repository
  31. Owner *models.User
  32. Commit *git.Commit
  33. Tag *git.Tag
  34. GitRepo *git.Repository
  35. BranchName string
  36. TagName string
  37. TreeName string
  38. CommitID string
  39. RepoLink string
  40. CloneLink models.CloneLink
  41. CommitsCount int64
  42. Mirror *models.Mirror
  43. }
  44. // Context represents context of a request.
  45. type Context struct {
  46. *macaron.Context
  47. Cache cache.Cache
  48. csrf csrf.CSRF
  49. Flash *session.Flash
  50. Session session.Store
  51. User *models.User
  52. IsSigned bool
  53. IsBasicAuth bool
  54. Repo *RepoContext
  55. Org struct {
  56. IsOwner bool
  57. IsMember bool
  58. IsAdminTeam bool // In owner team or team that has admin permission level.
  59. Organization *models.User
  60. OrgLink string
  61. Team *models.Team
  62. }
  63. }
  64. // IsOwner returns true if current user is the owner of repository.
  65. func (r *RepoContext) IsOwner() bool {
  66. return r.AccessMode >= models.ACCESS_MODE_OWNER
  67. }
  68. // IsAdmin returns true if current user has admin or higher access of repository.
  69. func (r *RepoContext) IsAdmin() bool {
  70. return r.AccessMode >= models.ACCESS_MODE_ADMIN
  71. }
  72. // IsPusher returns true if current user has write or higher access of repository.
  73. func (r *RepoContext) IsPusher() bool {
  74. return r.AccessMode >= models.ACCESS_MODE_WRITE
  75. }
  76. // Return if the current user has read access for this repository
  77. func (r *RepoContext) HasAccess() bool {
  78. return r.AccessMode >= models.ACCESS_MODE_READ
  79. }
  80. // HasError returns true if error occurs in form validation.
  81. func (ctx *Context) HasApiError() bool {
  82. hasErr, ok := ctx.Data["HasError"]
  83. if !ok {
  84. return false
  85. }
  86. return hasErr.(bool)
  87. }
  88. func (ctx *Context) GetErrMsg() string {
  89. return ctx.Data["ErrorMsg"].(string)
  90. }
  91. // HasError returns true if error occurs in form validation.
  92. func (ctx *Context) HasError() bool {
  93. hasErr, ok := ctx.Data["HasError"]
  94. if !ok {
  95. return false
  96. }
  97. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  98. ctx.Data["Flash"] = ctx.Flash
  99. return hasErr.(bool)
  100. }
  101. // HasValue returns true if value of given name exists.
  102. func (ctx *Context) HasValue(name string) bool {
  103. _, ok := ctx.Data[name]
  104. return ok
  105. }
  106. // HTML calls Context.HTML and converts template name to string.
  107. func (ctx *Context) HTML(status int, name base.TplName) {
  108. ctx.Context.HTML(status, string(name))
  109. }
  110. // RenderWithErr used for page has form validation but need to prompt error to users.
  111. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  112. if form != nil {
  113. auth.AssignForm(form, ctx.Data)
  114. }
  115. ctx.Flash.ErrorMsg = msg
  116. ctx.Data["Flash"] = ctx.Flash
  117. ctx.HTML(200, tpl)
  118. }
  119. // Handle handles and logs error by given status.
  120. func (ctx *Context) Handle(status int, title string, err error) {
  121. if err != nil {
  122. log.Error(4, "%s: %v", title, err)
  123. if macaron.Env != macaron.PROD {
  124. ctx.Data["ErrorMsg"] = err
  125. }
  126. }
  127. switch status {
  128. case 404:
  129. ctx.Data["Title"] = "Page Not Found"
  130. case 500:
  131. ctx.Data["Title"] = "Internal Server Error"
  132. }
  133. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  134. }
  135. func (ctx *Context) HandleText(status int, title string) {
  136. if (status/100 == 4) || (status/100 == 5) {
  137. log.Error(4, "%s", title)
  138. }
  139. ctx.PlainText(status, []byte(title))
  140. }
  141. // APIError logs error with title if status is 500.
  142. func (ctx *Context) APIError(status int, title string, obj interface{}) {
  143. var message string
  144. if err, ok := obj.(error); ok {
  145. message = err.Error()
  146. } else {
  147. message = obj.(string)
  148. }
  149. if status == 500 {
  150. log.Error(4, "%s: %s", title, message)
  151. }
  152. ctx.JSON(status, map[string]string{
  153. "message": message,
  154. "url": base.DOC_URL,
  155. })
  156. }
  157. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  158. modtime := time.Now()
  159. for _, p := range params {
  160. switch v := p.(type) {
  161. case time.Time:
  162. modtime = v
  163. }
  164. }
  165. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  166. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  167. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  168. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  169. ctx.Resp.Header().Set("Expires", "0")
  170. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  171. ctx.Resp.Header().Set("Pragma", "public")
  172. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  173. }
  174. // Contexter initializes a classic context for a request.
  175. func Contexter() macaron.Handler {
  176. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  177. ctx := &Context{
  178. Context: c,
  179. Cache: cache,
  180. csrf: x,
  181. Flash: f,
  182. Session: sess,
  183. Repo: &RepoContext{},
  184. }
  185. // Compute current URL for real-time change language.
  186. ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/")
  187. ctx.Data["PageStartTime"] = time.Now()
  188. // Get user from session if logined.
  189. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  190. if ctx.User != nil {
  191. ctx.IsSigned = true
  192. ctx.Data["IsSigned"] = ctx.IsSigned
  193. ctx.Data["SignedUser"] = ctx.User
  194. ctx.Data["SignedUserID"] = ctx.User.Id
  195. ctx.Data["SignedUserName"] = ctx.User.Name
  196. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  197. } else {
  198. ctx.Data["SignedUserID"] = 0
  199. ctx.Data["SignedUserName"] = ""
  200. }
  201. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  202. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  203. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  204. ctx.Handle(500, "ParseMultipartForm", err)
  205. return
  206. }
  207. }
  208. ctx.Data["CsrfToken"] = x.GetToken()
  209. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  210. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  211. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  212. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  213. c.Map(ctx)
  214. }
  215. }