context.go 6.1 KB

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