context.go 7.4 KB

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