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 8.5 kB

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