context.go 9.7 KB

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