context.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. log "gopkg.in/clog.v1"
  17. "gopkg.in/macaron.v1"
  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/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.Trace("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. switch status {
  79. case 404:
  80. ctx.Data["Title"] = "Page Not Found"
  81. case 500:
  82. ctx.Data["Title"] = "Internal Server Error"
  83. log.Error(2, "%s: %v", title, err)
  84. if !setting.ProdMode || (ctx.IsSigned && ctx.User.IsAdmin) {
  85. ctx.Data["ErrorMsg"] = err
  86. }
  87. }
  88. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  89. }
  90. // NotFound simply renders the 404 page.
  91. func (ctx *Context) NotFound() {
  92. ctx.Handle(404, "", nil)
  93. }
  94. // NotFoundOrServerError use error check function to determine if the error
  95. // is about not found. It responses with 404 status code for not found error,
  96. // or error context description for logging purpose of 500 server error.
  97. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  98. if errck(err) {
  99. ctx.NotFound()
  100. return
  101. }
  102. ctx.Handle(500, title, err)
  103. }
  104. func (ctx *Context) HandleText(status int, title string) {
  105. ctx.PlainText(status, []byte(title))
  106. }
  107. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  108. modtime := time.Now()
  109. for _, p := range params {
  110. switch v := p.(type) {
  111. case time.Time:
  112. modtime = v
  113. }
  114. }
  115. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  116. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  117. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  118. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  119. ctx.Resp.Header().Set("Expires", "0")
  120. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  121. ctx.Resp.Header().Set("Pragma", "public")
  122. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  123. }
  124. // Contexter initializes a classic context for a request.
  125. func Contexter() macaron.Handler {
  126. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  127. ctx := &Context{
  128. Context: c,
  129. Cache: cache,
  130. csrf: x,
  131. Flash: f,
  132. Session: sess,
  133. Repo: &Repository{
  134. PullRequest: &PullRequest{},
  135. },
  136. Org: &Organization{},
  137. }
  138. if len(setting.HTTP.AccessControlAllowOrigin) > 0 {
  139. ctx.Header().Set("Access-Control-Allow-Origin", setting.HTTP.AccessControlAllowOrigin)
  140. }
  141. // Compute current URL for real-time change language.
  142. ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/")
  143. ctx.Data["PageStartTime"] = time.Now()
  144. // Get user from session if logined.
  145. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  146. if ctx.User != nil {
  147. ctx.IsSigned = true
  148. ctx.Data["IsSigned"] = ctx.IsSigned
  149. ctx.Data["SignedUser"] = ctx.User
  150. ctx.Data["SignedUserID"] = ctx.User.ID
  151. ctx.Data["SignedUserName"] = ctx.User.Name
  152. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  153. } else {
  154. ctx.Data["SignedUserID"] = 0
  155. ctx.Data["SignedUserName"] = ""
  156. }
  157. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  158. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  159. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  160. ctx.Handle(500, "ParseMultipartForm", err)
  161. return
  162. }
  163. }
  164. ctx.Data["CsrfToken"] = x.GetToken()
  165. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  166. log.Trace("Session ID: %s", sess.ID())
  167. log.Trace("CSRF Token: %v", ctx.Data["CsrfToken"])
  168. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  169. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  170. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  171. c.Map(ctx)
  172. }
  173. }