You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 7.3 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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"
  8. "html/template"
  9. "io"
  10. "net/http"
  11. "path"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/Unknwon/com"
  20. "github.com/go-macaron/cache"
  21. "github.com/go-macaron/csrf"
  22. "github.com/go-macaron/i18n"
  23. "github.com/go-macaron/session"
  24. macaron "gopkg.in/macaron.v1"
  25. )
  26. // Context represents context of a request.
  27. type Context struct {
  28. *macaron.Context
  29. Cache cache.Cache
  30. csrf csrf.CSRF
  31. Flash *session.Flash
  32. Session session.Store
  33. Link string // current request URL
  34. User *models.User
  35. IsSigned bool
  36. IsBasicAuth bool
  37. Repo *Repository
  38. Org *Organization
  39. }
  40. // HasAPIError returns true if error occurs in form validation.
  41. func (ctx *Context) HasAPIError() bool {
  42. hasErr, ok := ctx.Data["HasError"]
  43. if !ok {
  44. return false
  45. }
  46. return hasErr.(bool)
  47. }
  48. // GetErrMsg returns error message
  49. func (ctx *Context) GetErrMsg() string {
  50. return ctx.Data["ErrorMsg"].(string)
  51. }
  52. // HasError returns true if error occurs in form validation.
  53. func (ctx *Context) HasError() bool {
  54. hasErr, ok := ctx.Data["HasError"]
  55. if !ok {
  56. return false
  57. }
  58. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  59. ctx.Data["Flash"] = ctx.Flash
  60. return hasErr.(bool)
  61. }
  62. // HasValue returns true if value of given name exists.
  63. func (ctx *Context) HasValue(name string) bool {
  64. _, ok := ctx.Data[name]
  65. return ok
  66. }
  67. // HTML calls Context.HTML and converts template name to string.
  68. func (ctx *Context) HTML(status int, name base.TplName) {
  69. log.Debug("Template: %s", name)
  70. ctx.Context.HTML(status, string(name))
  71. }
  72. // RenderWithErr used for page has form validation but need to prompt error to users.
  73. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  74. if form != nil {
  75. auth.AssignForm(form, ctx.Data)
  76. }
  77. ctx.Flash.ErrorMsg = msg
  78. ctx.Data["Flash"] = ctx.Flash
  79. ctx.HTML(200, tpl)
  80. }
  81. // Handle handles and logs error by given status.
  82. func (ctx *Context) Handle(status int, title string, err error) {
  83. if err != nil {
  84. log.Error(4, "%s: %v", title, err)
  85. if macaron.Env != macaron.PROD {
  86. ctx.Data["ErrorMsg"] = err
  87. }
  88. }
  89. switch status {
  90. case 404:
  91. ctx.Data["Title"] = "Page Not Found"
  92. case 500:
  93. ctx.Data["Title"] = "Internal Server Error"
  94. }
  95. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  96. }
  97. // NotFoundOrServerError use error check function to determine if the error
  98. // is about not found. It responses with 404 status code for not found error,
  99. // or error context description for logging purpose of 500 server error.
  100. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  101. if errck(err) {
  102. ctx.Handle(404, title, err)
  103. return
  104. }
  105. ctx.Handle(500, title, err)
  106. }
  107. // HandleText handles HTTP status code
  108. func (ctx *Context) HandleText(status int, title string) {
  109. if (status/100 == 4) || (status/100 == 5) {
  110. log.Error(4, "%s", title)
  111. }
  112. ctx.PlainText(status, []byte(title))
  113. }
  114. // ServeContent serves content to http request
  115. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  116. modtime := time.Now()
  117. for _, p := range params {
  118. switch v := p.(type) {
  119. case time.Time:
  120. modtime = v
  121. }
  122. }
  123. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  124. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  125. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  126. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  127. ctx.Resp.Header().Set("Expires", "0")
  128. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  129. ctx.Resp.Header().Set("Pragma", "public")
  130. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  131. }
  132. // Contexter initializes a classic context for a request.
  133. func Contexter() macaron.Handler {
  134. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  135. ctx := &Context{
  136. Context: c,
  137. Cache: cache,
  138. csrf: x,
  139. Flash: f,
  140. Session: sess,
  141. Link: setting.AppSubURL + strings.TrimSuffix(c.Req.URL.Path, "/"),
  142. Repo: &Repository{
  143. PullRequest: &PullRequest{},
  144. },
  145. Org: &Organization{},
  146. }
  147. c.Data["Link"] = ctx.Link
  148. ctx.Data["PageStartTime"] = time.Now()
  149. // Quick responses appropriate go-get meta with status 200
  150. // regardless of if user have access to the repository,
  151. // or the repository does not exist at all.
  152. // This is particular a workaround for "go get" command which does not respect
  153. // .netrc file.
  154. if ctx.Query("go-get") == "1" {
  155. ownerName := c.Params(":username")
  156. repoName := c.Params(":reponame")
  157. branchName := "master"
  158. owner, err := models.GetUserByName(ownerName)
  159. if err == nil {
  160. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  161. if err == nil && len(repo.DefaultBranch) > 0 {
  162. branchName = repo.DefaultBranch
  163. }
  164. }
  165. prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName)
  166. c.PlainText(http.StatusOK, []byte(com.Expand(`
  167. <html>
  168. <head>
  169. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  170. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  171. </head>
  172. <body>
  173. go get {GoGetImport}
  174. </body>
  175. </html>
  176. `, map[string]string{
  177. "GoGetImport": ComposeGoGetImport(ownerName, strings.TrimSuffix(repoName, ".git")),
  178. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  179. "GoDocDirectory": prefix + "{/dir}",
  180. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  181. })))
  182. return
  183. }
  184. // Get user from session if logged in.
  185. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  186. if ctx.User != nil {
  187. ctx.IsSigned = true
  188. ctx.Data["IsSigned"] = ctx.IsSigned
  189. ctx.Data["SignedUser"] = ctx.User
  190. ctx.Data["SignedUserID"] = ctx.User.ID
  191. ctx.Data["SignedUserName"] = ctx.User.Name
  192. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  193. } else {
  194. ctx.Data["SignedUserID"] = 0
  195. ctx.Data["SignedUserName"] = ""
  196. }
  197. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  198. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  199. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  200. ctx.Handle(500, "ParseMultipartForm", err)
  201. return
  202. }
  203. }
  204. ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
  205. ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken())
  206. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  207. log.Debug("Session ID: %s", sess.ID())
  208. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  209. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  210. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  211. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  212. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  213. c.Map(ctx)
  214. }
  215. }