context.go 6.2 KB

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