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.

context.go 11KB

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