context.go 6.3 KB

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