context.go 9.1 KB

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