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

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