context.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. "io"
  11. "net/http"
  12. "path"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. raven "github.com/getsentry/raven-go"
  17. "github.com/go-macaron/cache"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/i18n"
  20. "github.com/go-macaron/session"
  21. log "gopkg.in/clog.v1"
  22. "gopkg.in/macaron.v1"
  23. )
  24. // Context represents context of a request.
  25. type Context struct {
  26. *macaron.Context
  27. Cache cache.Cache
  28. csrf csrf.CSRF
  29. Flash *session.Flash
  30. Session session.Store
  31. Link string // Current request URL
  32. User *models.User
  33. IsLogged bool
  34. IsBasicAuth bool
  35. IsTokenAuth 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. raven.CaptureErrorAndWait(err, nil)
  147. log.Error(3, "%s: %v", title, err)
  148. if !setting.ProdMode || (c.IsLogged && c.User.IsAdmin) {
  149. c.Data["ErrorMsg"] = err
  150. }
  151. }
  152. c.HTML(status, fmt.Sprintf("status/%d", status))
  153. }
  154. // NotFound renders the 404 page.
  155. func (c *Context) NotFound() {
  156. c.Handle(http.StatusNotFound, "", nil)
  157. }
  158. // ServerError renders the 500 page.
  159. func (c *Context) ServerError(title string, err error) {
  160. c.Handle(http.StatusInternalServerError, title, err)
  161. }
  162. // NotFoundOrServerError use error check function to determine if the error
  163. // is about not found. It responses with 404 status code for not found error,
  164. // or error context description for logging purpose of 500 server error.
  165. func (c *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  166. if errck(err) {
  167. c.NotFound()
  168. return
  169. }
  170. c.ServerError(title, err)
  171. }
  172. func (c *Context) HandleText(status int, title string) {
  173. c.PlainText(status, []byte(title))
  174. }
  175. func (c *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. c.Resp.Header().Set("Content-Description", "File Transfer")
  184. c.Resp.Header().Set("Content-Type", "application/octet-stream")
  185. c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  186. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  187. c.Resp.Header().Set("Expires", "0")
  188. c.Resp.Header().Set("Cache-Control", "must-revalidate")
  189. c.Resp.Header().Set("Pragma", "public")
  190. http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
  191. }
  192. // Contexter initializes a classic context for a request.
  193. func Contexter() macaron.Handler {
  194. return func(ctx *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  195. c := &Context{
  196. Context: ctx,
  197. Cache: cache,
  198. csrf: x,
  199. Flash: f,
  200. Session: sess,
  201. Link: setting.AppSubURL + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
  202. Repo: &Repository{
  203. PullRequest: &PullRequest{},
  204. },
  205. Org: &Organization{},
  206. }
  207. if strings.Title(macaron.Env) == "Development" {
  208. c.Data["Lab"] = 1
  209. } else {
  210. c.Data["Lab"] = 0
  211. }
  212. c.Data["Link"] = template.EscapePound(c.Link)
  213. c.Data["PageStartTime"] = time.Now()
  214. // Quick responses appropriate go-get meta with status 200
  215. // regardless of if user have access to the repository,
  216. // or the repository does not exist at all.
  217. // This is particular a workaround for "go get" command which does not respect
  218. // .netrc file.
  219. if c.Query("go-get") == "1" {
  220. ownerName := c.Params(":username")
  221. repoName := c.Params(":reponame")
  222. branchName := "master"
  223. owner, err := models.GetUserByName(ownerName)
  224. if err != nil {
  225. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  226. return
  227. }
  228. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  229. if err == nil && len(repo.DefaultBranch) > 0 {
  230. branchName = repo.DefaultBranch
  231. }
  232. prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName)
  233. c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
  234. <html>
  235. <head>
  236. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  237. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  238. </head>
  239. <body>
  240. go get {GoGetImport}
  241. </body>
  242. </html>
  243. `, map[string]string{
  244. "GoGetImport": path.Join(setting.Domain, setting.AppSubURL, repo.FullName()),
  245. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  246. "GoDocDirectory": prefix + "{/dir}",
  247. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  248. })))
  249. return
  250. }
  251. if len(setting.HTTP.AccessControlAllowOrigin) > 0 {
  252. c.Header().Set("Access-Control-Allow-Origin", setting.HTTP.AccessControlAllowOrigin)
  253. c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
  254. c.Header().Set("Access-Control-Max-Age", "3600")
  255. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  256. }
  257. // Get user from session or header when possible
  258. c.User, c.IsBasicAuth, c.IsTokenAuth = auth.SignedInUser(c.Context, c.Session)
  259. if c.User != nil {
  260. c.IsLogged = true
  261. c.Data["IsLogged"] = c.IsLogged
  262. c.Data["LoggedUser"] = c.User
  263. c.Data["LoggedUserID"] = c.User.ID
  264. c.Data["LoggedUserName"] = c.User.Name
  265. c.Data["IsAdmin"] = c.User.IsAdmin
  266. c.Data["IsStaff"] = c.User.IsStaff
  267. c.Data["IsIntern"] = c.User.IsIntern
  268. c.Data["IsBeta"] = c.User.IsBeta
  269. } else {
  270. c.Data["LoggedUserID"] = 0
  271. c.Data["LoggedUserName"] = ""
  272. }
  273. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  274. if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
  275. if err := c.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  276. c.ServerError("ParseMultipartForm", err)
  277. return
  278. }
  279. }
  280. c.Data["CSRFToken"] = x.GetToken()
  281. c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  282. log.Trace("Session ID: %s", sess.ID())
  283. log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
  284. c.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  285. ctx.Map(c)
  286. }
  287. }