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.

context.go 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. "path"
  11. "strings"
  12. "time"
  13. "github.com/Unknwon/macaron"
  14. "github.com/macaron-contrib/i18n"
  15. "github.com/macaron-contrib/session"
  16. "github.com/gogits/gogs/models"
  17. "github.com/gogits/gogs/modules/auth"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/git"
  20. "github.com/gogits/gogs/modules/log"
  21. "github.com/gogits/gogs/modules/setting"
  22. )
  23. // Context represents context of a request.
  24. type Context struct {
  25. *macaron.Context
  26. i18n.Locale
  27. Flash *session.Flash
  28. Session session.Store
  29. User *models.User
  30. IsSigned bool
  31. csrfToken string
  32. Repo struct {
  33. IsOwner bool
  34. IsTrueOwner bool
  35. IsWatching bool
  36. IsBranch bool
  37. IsTag bool
  38. IsCommit bool
  39. HasAccess bool
  40. Repository *models.Repository
  41. Owner *models.User
  42. Commit *git.Commit
  43. Tag *git.Tag
  44. GitRepo *git.Repository
  45. BranchName string
  46. TagName string
  47. CommitId string
  48. RepoLink string
  49. CloneLink struct {
  50. SSH string
  51. HTTPS string
  52. Git string
  53. }
  54. CommitsCount int
  55. Mirror *models.Mirror
  56. }
  57. }
  58. // Query querys form parameter.
  59. func (ctx *Context) Query(name string) string {
  60. ctx.Req.ParseForm()
  61. return ctx.Req.Form.Get(name)
  62. }
  63. // func (ctx *Context) Param(name string) string {
  64. // return ctx.p[name]
  65. // }
  66. // HasError returns true if error occurs in form validation.
  67. func (ctx *Context) HasApiError() bool {
  68. hasErr, ok := ctx.Data["HasError"]
  69. if !ok {
  70. return false
  71. }
  72. return hasErr.(bool)
  73. }
  74. func (ctx *Context) GetErrMsg() string {
  75. return ctx.Data["ErrorMsg"].(string)
  76. }
  77. // HasError returns true if error occurs in form validation.
  78. func (ctx *Context) HasError() bool {
  79. hasErr, ok := ctx.Data["HasError"]
  80. if !ok {
  81. return false
  82. }
  83. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  84. ctx.Data["Flash"] = ctx.Flash
  85. return hasErr.(bool)
  86. }
  87. // HTML calls render.HTML underlying but reduce one argument.
  88. func (ctx *Context) HTML(status int, name base.TplName) {
  89. ctx.Render.HTML(status, string(name), ctx.Data)
  90. }
  91. // RenderWithErr used for page has form validation but need to prompt error to users.
  92. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  93. if form != nil {
  94. auth.AssignForm(form, ctx.Data)
  95. }
  96. ctx.Flash.ErrorMsg = msg
  97. ctx.Data["Flash"] = ctx.Flash
  98. ctx.HTML(200, tpl)
  99. }
  100. // Handle handles and logs error by given status.
  101. func (ctx *Context) Handle(status int, title string, err error) {
  102. if err != nil {
  103. log.Error(4, "%s: %v", title, err)
  104. if macaron.Env != macaron.PROD {
  105. ctx.Data["ErrorMsg"] = err
  106. }
  107. }
  108. switch status {
  109. case 404:
  110. ctx.Data["Title"] = "Page Not Found"
  111. case 500:
  112. ctx.Data["Title"] = "Internal Server Error"
  113. }
  114. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  115. }
  116. func (ctx *Context) CsrfToken() string {
  117. if len(ctx.csrfToken) > 0 {
  118. return ctx.csrfToken
  119. }
  120. token := ctx.GetCookie("_csrf")
  121. if len(token) == 0 {
  122. token = base.GetRandomString(30)
  123. ctx.SetCookie("_csrf", token)
  124. }
  125. ctx.csrfToken = token
  126. return token
  127. }
  128. func (ctx *Context) CsrfTokenValid() bool {
  129. token := ctx.Query("_csrf")
  130. if token == "" {
  131. token = ctx.Req.Header.Get("X-Csrf-Token")
  132. }
  133. if token == "" {
  134. return false
  135. } else if ctx.csrfToken != token {
  136. return false
  137. }
  138. return true
  139. }
  140. func (ctx *Context) ServeFile(file string, names ...string) {
  141. var name string
  142. if len(names) > 0 {
  143. name = names[0]
  144. } else {
  145. name = path.Base(file)
  146. }
  147. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  148. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  149. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  150. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  151. ctx.Resp.Header().Set("Expires", "0")
  152. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  153. ctx.Resp.Header().Set("Pragma", "public")
  154. http.ServeFile(ctx.Resp, ctx.Req, file)
  155. }
  156. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  157. modtime := time.Now()
  158. for _, p := range params {
  159. switch v := p.(type) {
  160. case time.Time:
  161. modtime = v
  162. }
  163. }
  164. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  165. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  166. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  167. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  168. ctx.Resp.Header().Set("Expires", "0")
  169. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  170. ctx.Resp.Header().Set("Pragma", "public")
  171. http.ServeContent(ctx.Resp, ctx.Req, name, modtime, r)
  172. }
  173. // Contexter initializes a classic context for a request.
  174. func Contexter() macaron.Handler {
  175. return func(c *macaron.Context, l i18n.Locale, sess session.Store, f *session.Flash) {
  176. ctx := &Context{
  177. Context: c,
  178. Locale: l,
  179. Flash: f,
  180. Session: sess,
  181. }
  182. // Cache: setting.Cache,
  183. // Compute current URL for real-time change language.
  184. link := ctx.Req.RequestURI
  185. i := strings.Index(link, "?")
  186. if i > -1 {
  187. link = link[:i]
  188. }
  189. ctx.Data["Link"] = link
  190. ctx.Data["PageStartTime"] = time.Now()
  191. // Get user from session if logined.
  192. ctx.User = auth.SignedInUser(ctx.Req.Header, ctx.Session)
  193. if ctx.User != nil {
  194. ctx.IsSigned = true
  195. ctx.Data["IsSigned"] = ctx.IsSigned
  196. ctx.Data["SignedUser"] = ctx.User
  197. ctx.Data["SignedUserId"] = ctx.User.Id
  198. ctx.Data["SignedUserName"] = ctx.User.Name
  199. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  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. // get or create csrf token
  209. ctx.Data["CsrfToken"] = ctx.CsrfToken()
  210. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.csrfToken + `">`)
  211. c.Map(ctx)
  212. }
  213. }