context.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 context
  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/log"
  21. "github.com/gogits/gogs/modules/setting"
  22. )
  23. // Context represents context of a request.
  24. type Context struct {
  25. *macaron.Context
  26. Cache cache.Cache
  27. csrf csrf.CSRF
  28. Flash *session.Flash
  29. Session session.Store
  30. User *models.User
  31. IsSigned bool
  32. IsBasicAuth bool
  33. Repo *Repository
  34. Org *Organization
  35. }
  36. // HasError returns true if error occurs in form validation.
  37. func (ctx *Context) HasApiError() bool {
  38. hasErr, ok := ctx.Data["HasError"]
  39. if !ok {
  40. return false
  41. }
  42. return hasErr.(bool)
  43. }
  44. func (ctx *Context) GetErrMsg() string {
  45. return ctx.Data["ErrorMsg"].(string)
  46. }
  47. // HasError returns true if error occurs in form validation.
  48. func (ctx *Context) HasError() bool {
  49. hasErr, ok := ctx.Data["HasError"]
  50. if !ok {
  51. return false
  52. }
  53. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  54. ctx.Data["Flash"] = ctx.Flash
  55. return hasErr.(bool)
  56. }
  57. // HasValue returns true if value of given name exists.
  58. func (ctx *Context) HasValue(name string) bool {
  59. _, ok := ctx.Data[name]
  60. return ok
  61. }
  62. // HTML calls Context.HTML and converts template name to string.
  63. func (ctx *Context) HTML(status int, name base.TplName) {
  64. log.Debug("Template: %s", name)
  65. ctx.Context.HTML(status, string(name))
  66. }
  67. // RenderWithErr used for page has form validation but need to prompt error to users.
  68. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  69. if form != nil {
  70. auth.AssignForm(form, ctx.Data)
  71. }
  72. ctx.Flash.ErrorMsg = msg
  73. ctx.Data["Flash"] = ctx.Flash
  74. ctx.HTML(200, tpl)
  75. }
  76. // Handle handles and logs error by given status.
  77. func (ctx *Context) Handle(status int, title string, err error) {
  78. if err != nil {
  79. log.Error(4, "%s: %v", title, err)
  80. if macaron.Env != macaron.PROD {
  81. ctx.Data["ErrorMsg"] = err
  82. }
  83. }
  84. switch status {
  85. case 404:
  86. ctx.Data["Title"] = "Page Not Found"
  87. case 500:
  88. ctx.Data["Title"] = "Internal Server Error"
  89. }
  90. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  91. }
  92. // HandleError use error check function to determine if server should
  93. // response as client input error or server internal error.
  94. // It responses with given status code for client error,
  95. // or error context description for logging purpose of server error.
  96. func (ctx *Context) HandleError(title string, errck func(error) bool, err error, status int) {
  97. if errck(err) {
  98. ctx.Error(status, err.Error())
  99. return
  100. }
  101. ctx.Handle(500, title, err)
  102. }
  103. func (ctx *Context) HandleText(status int, title string) {
  104. if (status/100 == 4) || (status/100 == 5) {
  105. log.Error(4, "%s", title)
  106. }
  107. ctx.PlainText(status, []byte(title))
  108. }
  109. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  110. modtime := time.Now()
  111. for _, p := range params {
  112. switch v := p.(type) {
  113. case time.Time:
  114. modtime = v
  115. }
  116. }
  117. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  118. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  119. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  120. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  121. ctx.Resp.Header().Set("Expires", "0")
  122. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  123. ctx.Resp.Header().Set("Pragma", "public")
  124. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  125. }
  126. // Contexter initializes a classic context for a request.
  127. func Contexter() macaron.Handler {
  128. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  129. ctx := &Context{
  130. Context: c,
  131. Cache: cache,
  132. csrf: x,
  133. Flash: f,
  134. Session: sess,
  135. Repo: &Repository{
  136. PullRequest: &PullRequest{},
  137. },
  138. Org: &Organization{},
  139. }
  140. // Compute current URL for real-time change language.
  141. ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/")
  142. ctx.Data["PageStartTime"] = time.Now()
  143. // Get user from session if logined.
  144. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  145. if ctx.User != nil {
  146. ctx.IsSigned = true
  147. ctx.Data["IsSigned"] = ctx.IsSigned
  148. ctx.Data["SignedUser"] = ctx.User
  149. ctx.Data["SignedUserID"] = ctx.User.ID
  150. ctx.Data["SignedUserName"] = ctx.User.Name
  151. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  152. } else {
  153. ctx.Data["SignedUserID"] = 0
  154. ctx.Data["SignedUserName"] = ""
  155. }
  156. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  157. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  158. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  159. ctx.Handle(500, "ParseMultipartForm", err)
  160. return
  161. }
  162. }
  163. ctx.Data["CsrfToken"] = x.GetToken()
  164. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  165. log.Debug("Session ID: %s", sess.ID())
  166. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  167. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  168. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  169. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  170. c.Map(ctx)
  171. }
  172. }