context.go 6.9 KB

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