context.go 9.5 KB

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