本站源代码
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

346 lines
10KB

  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. "code.gitea.io/gitea/modules/util"
  20. "gitea.com/macaron/cache"
  21. "gitea.com/macaron/csrf"
  22. "gitea.com/macaron/i18n"
  23. "gitea.com/macaron/macaron"
  24. "gitea.com/macaron/session"
  25. "github.com/unknwon/com"
  26. )
  27. // Context represents context of a request.
  28. type Context struct {
  29. *macaron.Context
  30. Cache cache.Cache
  31. csrf csrf.CSRF
  32. Flash *session.Flash
  33. Session session.Store
  34. Link string // current request URL
  35. EscapedLink string
  36. User *models.User
  37. IsSigned bool
  38. IsBasicAuth bool
  39. Repo *Repository
  40. Org *Organization
  41. }
  42. // IsUserSiteAdmin returns true if current user is a site admin
  43. func (ctx *Context) IsUserSiteAdmin() bool {
  44. return ctx.IsSigned && ctx.User.IsAdmin
  45. }
  46. // IsUserRepoOwner returns true if current user owns current repo
  47. func (ctx *Context) IsUserRepoOwner() bool {
  48. return ctx.Repo.IsOwner()
  49. }
  50. // IsUserRepoAdmin returns true if current user is admin in current repo
  51. func (ctx *Context) IsUserRepoAdmin() bool {
  52. return ctx.Repo.IsAdmin()
  53. }
  54. // IsUserRepoWriter returns true if current user has write privilege in current repo
  55. func (ctx *Context) IsUserRepoWriter(unitTypes []models.UnitType) bool {
  56. for _, unitType := range unitTypes {
  57. if ctx.Repo.CanWrite(unitType) {
  58. return true
  59. }
  60. }
  61. return false
  62. }
  63. // IsUserRepoReaderSpecific returns true if current user can read current repo's specific part
  64. func (ctx *Context) IsUserRepoReaderSpecific(unitType models.UnitType) bool {
  65. return ctx.Repo.CanRead(unitType)
  66. }
  67. // IsUserRepoReaderAny returns true if current user can read any part of current repo
  68. func (ctx *Context) IsUserRepoReaderAny() bool {
  69. return ctx.Repo.HasAccess()
  70. }
  71. // HasAPIError returns true if error occurs in form validation.
  72. func (ctx *Context) HasAPIError() bool {
  73. hasErr, ok := ctx.Data["HasError"]
  74. if !ok {
  75. return false
  76. }
  77. return hasErr.(bool)
  78. }
  79. // GetErrMsg returns error message
  80. func (ctx *Context) GetErrMsg() string {
  81. return ctx.Data["ErrorMsg"].(string)
  82. }
  83. // HasError returns true if error occurs in form validation.
  84. func (ctx *Context) HasError() bool {
  85. hasErr, ok := ctx.Data["HasError"]
  86. if !ok {
  87. return false
  88. }
  89. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  90. ctx.Data["Flash"] = ctx.Flash
  91. return hasErr.(bool)
  92. }
  93. // HasValue returns true if value of given name exists.
  94. func (ctx *Context) HasValue(name string) bool {
  95. _, ok := ctx.Data[name]
  96. return ok
  97. }
  98. // RedirectToFirst redirects to first not empty URL
  99. func (ctx *Context) RedirectToFirst(location ...string) {
  100. for _, loc := range location {
  101. if len(loc) == 0 {
  102. continue
  103. }
  104. u, err := url.Parse(loc)
  105. if err != nil || (u.Scheme != "" && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {
  106. continue
  107. }
  108. ctx.Redirect(loc)
  109. return
  110. }
  111. ctx.Redirect(setting.AppSubURL + "/")
  112. }
  113. // HTML calls Context.HTML and converts template name to string.
  114. func (ctx *Context) HTML(status int, name base.TplName) {
  115. log.Debug("Template: %s", name)
  116. ctx.Context.HTML(status, string(name))
  117. }
  118. // RenderWithErr used for page has form validation but need to prompt error to users.
  119. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  120. if form != nil {
  121. auth.AssignForm(form, ctx.Data)
  122. }
  123. ctx.Flash.ErrorMsg = msg
  124. ctx.Data["Flash"] = ctx.Flash
  125. ctx.HTML(200, tpl)
  126. }
  127. // NotFound displays a 404 (Not Found) page and prints the given error, if any.
  128. func (ctx *Context) NotFound(title string, err error) {
  129. ctx.notFoundInternal(title, err)
  130. }
  131. func (ctx *Context) notFoundInternal(title string, err error) {
  132. if err != nil {
  133. log.ErrorWithSkip(2, "%s: %v", title, err)
  134. if macaron.Env != macaron.PROD {
  135. ctx.Data["ErrorMsg"] = err
  136. }
  137. }
  138. ctx.Data["IsRepo"] = ctx.Repo.Repository != nil
  139. ctx.Data["Title"] = "Page Not Found"
  140. ctx.HTML(http.StatusNotFound, base.TplName("status/404"))
  141. }
  142. // ServerError displays a 500 (Internal Server Error) page and prints the given
  143. // error, if any.
  144. func (ctx *Context) ServerError(title string, err error) {
  145. ctx.serverErrorInternal(title, err)
  146. }
  147. func (ctx *Context) serverErrorInternal(title string, err error) {
  148. if err != nil {
  149. log.ErrorWithSkip(2, "%s: %v", title, err)
  150. if macaron.Env != macaron.PROD {
  151. ctx.Data["ErrorMsg"] = err
  152. }
  153. }
  154. ctx.Data["Title"] = "Internal Server Error"
  155. ctx.HTML(http.StatusInternalServerError, base.TplName("status/500"))
  156. }
  157. // NotFoundOrServerError use error check function to determine if the error
  158. // is about not found. It responses with 404 status code for not found error,
  159. // or error context description for logging purpose of 500 server error.
  160. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  161. if errck(err) {
  162. ctx.notFoundInternal(title, err)
  163. return
  164. }
  165. ctx.serverErrorInternal(title, err)
  166. }
  167. // HandleText handles HTTP status code
  168. func (ctx *Context) HandleText(status int, title string) {
  169. if (status/100 == 4) || (status/100 == 5) {
  170. log.Error("%s", title)
  171. }
  172. ctx.PlainText(status, []byte(title))
  173. }
  174. // ServeContent serves content to http request
  175. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  176. modtime := time.Now()
  177. for _, p := range params {
  178. switch v := p.(type) {
  179. case time.Time:
  180. modtime = v
  181. }
  182. }
  183. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  184. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  185. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  186. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  187. ctx.Resp.Header().Set("Expires", "0")
  188. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  189. ctx.Resp.Header().Set("Pragma", "public")
  190. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  191. }
  192. // Contexter initializes a classic context for a request.
  193. func Contexter() macaron.Handler {
  194. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  195. ctx := &Context{
  196. Context: c,
  197. Cache: cache,
  198. csrf: x,
  199. Flash: f,
  200. Session: sess,
  201. Link: setting.AppSubURL + strings.TrimSuffix(c.Req.URL.EscapedPath(), "/"),
  202. Repo: &Repository{
  203. PullRequest: &PullRequest{},
  204. },
  205. Org: &Organization{},
  206. }
  207. ctx.Data["Language"] = ctx.Locale.Language()
  208. c.Data["Link"] = ctx.Link
  209. ctx.Data["PageStartTime"] = time.Now()
  210. // Quick responses appropriate go-get meta with status 200
  211. // regardless of if user have access to the repository,
  212. // or the repository does not exist at all.
  213. // This is particular a workaround for "go get" command which does not respect
  214. // .netrc file.
  215. if ctx.Query("go-get") == "1" {
  216. ownerName := c.Params(":username")
  217. repoName := c.Params(":reponame")
  218. trimmedRepoName := strings.TrimSuffix(repoName, ".git")
  219. if ownerName == "" || trimmedRepoName == "" {
  220. _, _ = c.Write([]byte(`<!doctype html>
  221. <html>
  222. <body>
  223. invalid import path
  224. </body>
  225. </html>
  226. `))
  227. c.WriteHeader(400)
  228. return
  229. }
  230. branchName := "master"
  231. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  232. if err == nil && len(repo.DefaultBranch) > 0 {
  233. branchName = repo.DefaultBranch
  234. }
  235. prefix := setting.AppURL + path.Join(url.PathEscape(ownerName), url.PathEscape(repoName), "src", "branch", util.PathEscapeSegments(branchName))
  236. appURL, _ := url.Parse(setting.AppURL)
  237. insecure := ""
  238. if appURL.Scheme == string(setting.HTTP) {
  239. insecure = "--insecure "
  240. }
  241. c.Header().Set("Content-Type", "text/html")
  242. c.WriteHeader(http.StatusOK)
  243. _, _ = c.Write([]byte(com.Expand(`<!doctype html>
  244. <html>
  245. <head>
  246. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  247. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  248. </head>
  249. <body>
  250. go get {Insecure}{GoGetImport}
  251. </body>
  252. </html>
  253. `, map[string]string{
  254. "GoGetImport": ComposeGoGetImport(ownerName, trimmedRepoName),
  255. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  256. "GoDocDirectory": prefix + "{/dir}",
  257. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  258. "Insecure": insecure,
  259. })))
  260. return
  261. }
  262. // Get user from session if logged in.
  263. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  264. if ctx.User != nil {
  265. ctx.IsSigned = true
  266. ctx.Data["IsSigned"] = ctx.IsSigned
  267. ctx.Data["SignedUser"] = ctx.User
  268. ctx.Data["SignedUserID"] = ctx.User.ID
  269. ctx.Data["SignedUserName"] = ctx.User.Name
  270. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  271. } else {
  272. ctx.Data["SignedUserID"] = int64(0)
  273. ctx.Data["SignedUserName"] = ""
  274. }
  275. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  276. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  277. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  278. ctx.ServerError("ParseMultipartForm", err)
  279. return
  280. }
  281. }
  282. ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
  283. ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken())
  284. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  285. log.Debug("Session ID: %s", sess.ID())
  286. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  287. ctx.Data["IsLandingPageHome"] = setting.LandingPageURL == setting.LandingPageHome
  288. ctx.Data["IsLandingPageExplore"] = setting.LandingPageURL == setting.LandingPageExplore
  289. ctx.Data["IsLandingPageOrganizations"] = setting.LandingPageURL == setting.LandingPageOrganizations
  290. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  291. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  292. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  293. ctx.Data["EnableSwagger"] = setting.API.EnableSwagger
  294. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  295. c.Map(ctx)
  296. }
  297. }
上海开阖软件有限公司 沪ICP备12045867号-1