You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
6.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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/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. type RepoContext struct {
  25. AccessMode models.AccessMode
  26. IsWatching bool
  27. IsBranch bool
  28. IsTag bool
  29. IsCommit 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 int
  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. // 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.PlainText(status, []byte(title))
  136. }
  137. // APIError logs error with title if status is 500.
  138. func (ctx *Context) APIError(status int, title string, obj interface{}) {
  139. var message string
  140. if err, ok := obj.(error); ok {
  141. message = err.Error()
  142. } else {
  143. message = obj.(string)
  144. }
  145. if status == 500 {
  146. log.Error(4, "%s: %s", title, message)
  147. }
  148. ctx.JSON(status, map[string]string{
  149. "message": message,
  150. "url": base.DOC_URL,
  151. })
  152. }
  153. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  154. modtime := time.Now()
  155. for _, p := range params {
  156. switch v := p.(type) {
  157. case time.Time:
  158. modtime = v
  159. }
  160. }
  161. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  162. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  163. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  164. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  165. ctx.Resp.Header().Set("Expires", "0")
  166. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  167. ctx.Resp.Header().Set("Pragma", "public")
  168. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  169. }
  170. // Contexter initializes a classic context for a request.
  171. func Contexter() macaron.Handler {
  172. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  173. ctx := &Context{
  174. Context: c,
  175. Cache: cache,
  176. csrf: x,
  177. Flash: f,
  178. Session: sess,
  179. }
  180. // Compute current URL for real-time change language.
  181. ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/")
  182. ctx.Data["PageStartTime"] = time.Now()
  183. // Check auto-signin.
  184. if sess.Get("uid") == nil {
  185. if _, err := AutoSignIn(ctx); err != nil {
  186. ctx.Handle(500, "AutoSignIn", err)
  187. return
  188. }
  189. }
  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. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  213. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  214. c.Map(ctx)
  215. }
  216. }