Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

context.go 7.1KB

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