context.go 8.8 KB

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