context.go 8.7 KB

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