context.go 8.7 KB

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