context.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. // RawRedirect simply calls underlying Redirect method with no escape.
  118. func (c *Context) RawRedirect(location string, status ...int) {
  119. c.Context.Redirect(location, status...)
  120. }
  121. // Redirect responses redirection wtih given location and status.
  122. // It escapes special characters in the location string.
  123. func (c *Context) Redirect(location string, status ...int) {
  124. c.Context.Redirect(template.EscapePound(location), status...)
  125. }
  126. // SubURLRedirect responses redirection wtih given location and status.
  127. // It prepends setting.AppSubURL to the location string.
  128. func (c *Context) SubURLRedirect(location string, status ...int) {
  129. c.Redirect(setting.AppSubURL+location, status...)
  130. }
  131. // RenderWithErr used for page has form validation but need to prompt error to users.
  132. func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
  133. if f != nil {
  134. form.Assign(f, c.Data)
  135. }
  136. c.Flash.ErrorMsg = msg
  137. c.Data["Flash"] = c.Flash
  138. c.HTML(http.StatusOK, tpl)
  139. }
  140. // Handle handles and logs error by given status.
  141. func (c *Context) Handle(status int, title string, err error) {
  142. switch status {
  143. case http.StatusNotFound:
  144. c.Data["Title"] = "Page Not Found"
  145. case http.StatusInternalServerError:
  146. c.Data["Title"] = "Internal Server Error"
  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. c.Data["Link"] = template.EscapePound(c.Link)
  208. c.Data["PageStartTime"] = time.Now()
  209. // Quick responses appropriate go-get meta with status 200
  210. // regardless of if user have access to the repository,
  211. // or the repository does not exist at all.
  212. // This is particular a workaround for "go get" command which does not respect
  213. // .netrc file.
  214. if c.Query("go-get") == "1" {
  215. ownerName := c.Params(":username")
  216. repoName := c.Params(":reponame")
  217. branchName := "master"
  218. owner, err := models.GetUserByName(ownerName)
  219. if err != nil {
  220. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  221. return
  222. }
  223. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  224. if err == nil && len(repo.DefaultBranch) > 0 {
  225. branchName = repo.DefaultBranch
  226. }
  227. prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName)
  228. c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
  229. <html>
  230. <head>
  231. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  232. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  233. </head>
  234. <body>
  235. go get {GoGetImport}
  236. </body>
  237. </html>
  238. `, map[string]string{
  239. "GoGetImport": path.Join(setting.Domain, setting.AppSubURL, repo.FullName()),
  240. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  241. "GoDocDirectory": prefix + "{/dir}",
  242. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  243. })))
  244. return
  245. }
  246. if len(setting.HTTP.AccessControlAllowOrigin) > 0 {
  247. c.Header().Set("Access-Control-Allow-Origin", setting.HTTP.AccessControlAllowOrigin)
  248. c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
  249. c.Header().Set("Access-Control-Max-Age", "3600")
  250. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  251. }
  252. // Get user from session if logined.
  253. c.User, c.IsBasicAuth = auth.SignedInUser(c.Context, c.Session)
  254. if c.User != nil {
  255. c.IsLogged = true
  256. c.Data["IsLogged"] = c.IsLogged
  257. c.Data["LoggedUser"] = c.User
  258. c.Data["LoggedUserID"] = c.User.ID
  259. c.Data["LoggedUserName"] = c.User.Name
  260. c.Data["IsAdmin"] = c.User.IsAdmin
  261. } else {
  262. c.Data["LoggedUserID"] = 0
  263. c.Data["LoggedUserName"] = ""
  264. }
  265. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  266. if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
  267. if err := c.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  268. c.ServerError("ParseMultipartForm", err)
  269. return
  270. }
  271. }
  272. c.Data["CSRFToken"] = x.GetToken()
  273. c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  274. log.Trace("Session ID: %s", sess.ID())
  275. log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
  276. c.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  277. c.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  278. c.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  279. ctx.Map(c)
  280. }
  281. }