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 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. "github.com/Unknwon/com"
  21. "github.com/go-macaron/cache"
  22. "github.com/go-macaron/csrf"
  23. "github.com/go-macaron/i18n"
  24. "github.com/go-macaron/session"
  25. "gopkg.in/macaron.v1"
  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. branchName := "master"
  219. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  220. if err == nil && len(repo.DefaultBranch) > 0 {
  221. branchName = repo.DefaultBranch
  222. }
  223. prefix := setting.AppURL + path.Join(url.PathEscape(ownerName), url.PathEscape(repoName), "src", "branch", util.PathEscapeSegments(branchName))
  224. appURL, _ := url.Parse(setting.AppURL)
  225. insecure := ""
  226. if appURL.Scheme == string(setting.HTTP) {
  227. insecure = "--insecure "
  228. }
  229. c.Header().Set("Content-Type", "text/html")
  230. c.WriteHeader(http.StatusOK)
  231. _, _ = c.Write([]byte(com.Expand(`<!doctype html>
  232. <html>
  233. <head>
  234. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  235. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  236. </head>
  237. <body>
  238. go get {Insecure}{GoGetImport}
  239. </body>
  240. </html>
  241. `, map[string]string{
  242. "GoGetImport": ComposeGoGetImport(ownerName, strings.TrimSuffix(repoName, ".git")),
  243. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  244. "GoDocDirectory": prefix + "{/dir}",
  245. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  246. "Insecure": insecure,
  247. })))
  248. return
  249. }
  250. // Get user from session if logged in.
  251. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  252. if ctx.User != nil {
  253. ctx.IsSigned = true
  254. ctx.Data["IsSigned"] = ctx.IsSigned
  255. ctx.Data["SignedUser"] = ctx.User
  256. ctx.Data["SignedUserID"] = ctx.User.ID
  257. ctx.Data["SignedUserName"] = ctx.User.Name
  258. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  259. } else {
  260. ctx.Data["SignedUserID"] = int64(0)
  261. ctx.Data["SignedUserName"] = ""
  262. }
  263. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  264. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  265. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  266. ctx.ServerError("ParseMultipartForm", err)
  267. return
  268. }
  269. }
  270. ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
  271. ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken())
  272. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  273. log.Debug("Session ID: %s", sess.ID())
  274. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  275. ctx.Data["IsLandingPageHome"] = setting.LandingPageURL == setting.LandingPageHome
  276. ctx.Data["IsLandingPageExplore"] = setting.LandingPageURL == setting.LandingPageExplore
  277. ctx.Data["IsLandingPageOrganizations"] = setting.LandingPageURL == setting.LandingPageOrganizations
  278. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  279. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  280. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  281. ctx.Data["EnableSwagger"] = setting.API.EnableSwagger
  282. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  283. c.Map(ctx)
  284. }
  285. }