context.go 9.9 KB

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