context.go 6.4 KB

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