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.4 kB

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