context.go 7.2 KB

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