context.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. "fmt"
  7. "io"
  8. "net/http"
  9. "path"
  10. "strings"
  11. "time"
  12. "github.com/go-macaron/cache"
  13. "github.com/go-macaron/csrf"
  14. "github.com/go-macaron/i18n"
  15. "github.com/go-macaron/session"
  16. "github.com/unknwon/com"
  17. "gopkg.in/macaron.v1"
  18. log "unknwon.dev/clog/v2"
  19. "gogs.io/gogs/internal/auth"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/errutil"
  23. "gogs.io/gogs/internal/form"
  24. "gogs.io/gogs/internal/template"
  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. User *db.User
  35. IsLogged bool
  36. IsBasicAuth bool
  37. IsTokenAuth bool
  38. Repo *Repository
  39. Org *Organization
  40. }
  41. // RawTitle sets the "Title" field in template data.
  42. func (c *Context) RawTitle(title string) {
  43. c.Data["Title"] = title
  44. }
  45. // Title localizes the "Title" field in template data.
  46. func (c *Context) Title(locale string) {
  47. c.RawTitle(c.Tr(locale))
  48. }
  49. // PageIs sets "PageIsxxx" field in template data.
  50. func (c *Context) PageIs(name string) {
  51. c.Data["PageIs"+name] = true
  52. }
  53. // Require sets "Requirexxx" field in template data.
  54. func (c *Context) Require(name string) {
  55. c.Data["Require"+name] = true
  56. }
  57. func (c *Context) RequireHighlightJS() {
  58. c.Require("HighlightJS")
  59. }
  60. func (c *Context) RequireSimpleMDE() {
  61. c.Require("SimpleMDE")
  62. }
  63. func (c *Context) RequireAutosize() {
  64. c.Require("Autosize")
  65. }
  66. func (c *Context) RequireDropzone() {
  67. c.Require("Dropzone")
  68. }
  69. // FormErr sets "Err_xxx" field in template data.
  70. func (c *Context) FormErr(names ...string) {
  71. for i := range names {
  72. c.Data["Err_"+names[i]] = true
  73. }
  74. }
  75. // UserID returns ID of current logged in user.
  76. // It returns 0 if visitor is anonymous.
  77. func (c *Context) UserID() int64 {
  78. if !c.IsLogged {
  79. return 0
  80. }
  81. return c.User.ID
  82. }
  83. // HasError returns true if error occurs in form validation.
  84. func (c *Context) HasApiError() bool {
  85. hasErr, ok := c.Data["HasError"]
  86. if !ok {
  87. return false
  88. }
  89. return hasErr.(bool)
  90. }
  91. func (c *Context) GetErrMsg() string {
  92. return c.Data["ErrorMsg"].(string)
  93. }
  94. // HasError returns true if error occurs in form validation.
  95. func (c *Context) HasError() bool {
  96. hasErr, ok := c.Data["HasError"]
  97. if !ok {
  98. return false
  99. }
  100. c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
  101. c.Data["Flash"] = c.Flash
  102. return hasErr.(bool)
  103. }
  104. // HasValue returns true if value of given name exists.
  105. func (c *Context) HasValue(name string) bool {
  106. _, ok := c.Data[name]
  107. return ok
  108. }
  109. // HTML responses template with given status.
  110. func (c *Context) HTML(status int, name string) {
  111. log.Trace("Template: %s", name)
  112. c.Context.HTML(status, name)
  113. }
  114. // Success responses template with status http.StatusOK.
  115. func (c *Context) Success(name string) {
  116. c.HTML(http.StatusOK, name)
  117. }
  118. // JSONSuccess responses JSON with status http.StatusOK.
  119. func (c *Context) JSONSuccess(data interface{}) {
  120. c.JSON(http.StatusOK, data)
  121. }
  122. // RawRedirect simply calls underlying Redirect method with no escape.
  123. func (c *Context) RawRedirect(location string, status ...int) {
  124. c.Context.Redirect(location, status...)
  125. }
  126. // Redirect responses redirection with given location and status.
  127. // It escapes special characters in the location string.
  128. func (c *Context) Redirect(location string, status ...int) {
  129. c.Context.Redirect(template.EscapePound(location), status...)
  130. }
  131. // RedirectSubpath responses redirection with given location and status.
  132. // It prepends setting.Server.Subpath to the location string.
  133. func (c *Context) RedirectSubpath(location string, status ...int) {
  134. c.Redirect(conf.Server.Subpath+location, status...)
  135. }
  136. // RenderWithErr used for page has form validation but need to prompt error to users.
  137. func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
  138. if f != nil {
  139. form.Assign(f, c.Data)
  140. }
  141. c.Flash.ErrorMsg = msg
  142. c.Data["Flash"] = c.Flash
  143. c.HTML(http.StatusOK, tpl)
  144. }
  145. // NotFound renders the 404 page.
  146. func (c *Context) NotFound() {
  147. c.Title("status.page_not_found")
  148. c.HTML(http.StatusNotFound, fmt.Sprintf("status/%d", http.StatusNotFound))
  149. }
  150. // Error renders the 500 page.
  151. func (c *Context) Error(err error, msg string) {
  152. log.ErrorDepth(5, "%s: %v", msg, err)
  153. c.Title("status.internal_server_error")
  154. // Only in non-production mode or admin can see the actual error message.
  155. if !conf.IsProdMode() || (c.IsLogged && c.User.IsAdmin) {
  156. c.Data["ErrorMsg"] = err
  157. }
  158. c.HTML(http.StatusInternalServerError, fmt.Sprintf("status/%d", http.StatusInternalServerError))
  159. }
  160. // Errorf renders the 500 response with formatted message.
  161. func (c *Context) Errorf(err error, format string, args ...interface{}) {
  162. c.Error(err, fmt.Sprintf(format, args...))
  163. }
  164. // NotFoundOrError responses with 404 page for not found error and 500 page otherwise.
  165. func (c *Context) NotFoundOrError(err error, msg string) {
  166. if errutil.IsNotFound(err) {
  167. c.NotFound()
  168. return
  169. }
  170. c.Error(err, msg)
  171. }
  172. // NotFoundOrErrorf is same as NotFoundOrError but with formatted message.
  173. func (c *Context) NotFoundOrErrorf(err error, format string, args ...interface{}) {
  174. c.NotFoundOrError(err, fmt.Sprintf(format, args...))
  175. }
  176. func (c *Context) PlainText(status int, msg string) {
  177. c.Render.PlainText(status, []byte(msg))
  178. }
  179. func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  180. modtime := time.Now()
  181. for _, p := range params {
  182. switch v := p.(type) {
  183. case time.Time:
  184. modtime = v
  185. }
  186. }
  187. c.Resp.Header().Set("Content-Description", "File Transfer")
  188. c.Resp.Header().Set("Content-Type", "application/octet-stream")
  189. c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  190. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  191. c.Resp.Header().Set("Expires", "0")
  192. c.Resp.Header().Set("Cache-Control", "must-revalidate")
  193. c.Resp.Header().Set("Pragma", "public")
  194. http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
  195. }
  196. // Contexter initializes a classic context for a request.
  197. func Contexter() macaron.Handler {
  198. return func(ctx *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  199. c := &Context{
  200. Context: ctx,
  201. Cache: cache,
  202. csrf: x,
  203. Flash: f,
  204. Session: sess,
  205. Link: conf.Server.Subpath + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
  206. Repo: &Repository{
  207. PullRequest: &PullRequest{},
  208. },
  209. Org: &Organization{},
  210. }
  211. c.Data["Link"] = template.EscapePound(c.Link)
  212. c.Data["PageStartTime"] = time.Now()
  213. // Quick responses appropriate go-get meta with status 200
  214. // regardless of if user have access to the repository,
  215. // or the repository does not exist at all.
  216. // This is particular a workaround for "go get" command which does not respect
  217. // .netrc file.
  218. if c.Query("go-get") == "1" {
  219. ownerName := c.Params(":username")
  220. repoName := c.Params(":reponame")
  221. branchName := "master"
  222. owner, err := db.GetUserByName(ownerName)
  223. if err != nil {
  224. c.NotFoundOrError(err, "get user by name")
  225. return
  226. }
  227. repo, err := db.GetRepositoryByName(owner.ID, repoName)
  228. if err == nil && len(repo.DefaultBranch) > 0 {
  229. branchName = repo.DefaultBranch
  230. }
  231. prefix := conf.Server.ExternalURL + path.Join(ownerName, repoName, "src", branchName)
  232. insecureFlag := ""
  233. if !strings.HasPrefix(conf.Server.ExternalURL, "https://") {
  234. insecureFlag = "--insecure "
  235. }
  236. c.PlainText(http.StatusOK, com.Expand(`<!doctype html>
  237. <html>
  238. <head>
  239. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  240. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  241. </head>
  242. <body>
  243. go get {InsecureFlag}{GoGetImport}
  244. </body>
  245. </html>
  246. `, map[string]string{
  247. "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName),
  248. "CloneLink": db.ComposeHTTPSCloneURL(ownerName, repoName),
  249. "GoDocDirectory": prefix + "{/dir}",
  250. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  251. "InsecureFlag": insecureFlag,
  252. }))
  253. return
  254. }
  255. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  256. c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  257. c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
  258. c.Header().Set("Access-Control-Max-Age", "3600")
  259. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  260. }
  261. // Get user from session or header when possible
  262. c.User, c.IsBasicAuth, c.IsTokenAuth = auth.SignedInUser(c.Context, c.Session)
  263. if c.User != nil {
  264. c.IsLogged = true
  265. c.Data["IsLogged"] = c.IsLogged
  266. c.Data["LoggedUser"] = c.User
  267. c.Data["LoggedUserID"] = c.User.ID
  268. c.Data["LoggedUserName"] = c.User.Name
  269. c.Data["IsAdmin"] = c.User.IsAdmin
  270. } else {
  271. c.Data["LoggedUserID"] = 0
  272. c.Data["LoggedUserName"] = ""
  273. }
  274. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  275. if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
  276. if err := c.Req.ParseMultipartForm(conf.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  277. c.Error(err, "parse multipart form")
  278. return
  279. }
  280. }
  281. c.Data["CSRFToken"] = x.GetToken()
  282. c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  283. log.Trace("Session ID: %s", sess.ID())
  284. log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
  285. c.Data["ShowRegistrationButton"] = !conf.Auth.DisableRegistration
  286. c.Data["ShowFooterBranding"] = conf.Other.ShowFooterBranding
  287. c.renderNoticeBanner()
  288. ctx.Map(c)
  289. }
  290. }