context.go 6.4 KB

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