context.go 6.5 KB

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