context.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/go-macaron/cache"
  13. "github.com/go-macaron/csrf"
  14. "github.com/go-macaron/i18n"
  15. "github.com/go-macaron/session"
  16. "github.com/unknwon/com"
  17. "gopkg.in/macaron.v1"
  18. log "unknwon.dev/clog/v2"
  19. "gogs.io/gogs/internal/auth"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/db/errors"
  23. "gogs.io/gogs/internal/form"
  24. "gogs.io/gogs/internal/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 *db.User
  35. IsLogged bool
  36. IsBasicAuth bool
  37. IsTokenAuth bool
  38. Repo *Repository
  39. Org *Organization
  40. }
  41. // RawTitle sets the "Title" field in template data.
  42. func (c *Context) RawTitle(title string) {
  43. c.Data["Title"] = title
  44. }
  45. // Title localizes the "Title" field in template data.
  46. func (c *Context) Title(locale string) {
  47. c.RawTitle(c.Tr(locale))
  48. }
  49. // PageIs sets "PageIsxxx" field in template data.
  50. func (c *Context) PageIs(name string) {
  51. c.Data["PageIs"+name] = true
  52. }
  53. // Require sets "Requirexxx" field in template data.
  54. func (c *Context) Require(name string) {
  55. c.Data["Require"+name] = true
  56. }
  57. func (c *Context) RequireHighlightJS() {
  58. c.Require("HighlightJS")
  59. }
  60. func (c *Context) RequireSimpleMDE() {
  61. c.Require("SimpleMDE")
  62. }
  63. func (c *Context) RequireAutosize() {
  64. c.Require("Autosize")
  65. }
  66. func (c *Context) RequireDropzone() {
  67. c.Require("Dropzone")
  68. }
  69. // FormErr sets "Err_xxx" field in template data.
  70. func (c *Context) FormErr(names ...string) {
  71. for i := range names {
  72. c.Data["Err_"+names[i]] = true
  73. }
  74. }
  75. // UserID returns ID of current logged in user.
  76. // It returns 0 if visitor is anonymous.
  77. func (c *Context) UserID() int64 {
  78. if !c.IsLogged {
  79. return 0
  80. }
  81. return c.User.ID
  82. }
  83. // HasError returns true if error occurs in form validation.
  84. func (c *Context) HasApiError() bool {
  85. hasErr, ok := c.Data["HasError"]
  86. if !ok {
  87. return false
  88. }
  89. return hasErr.(bool)
  90. }
  91. func (c *Context) GetErrMsg() string {
  92. return c.Data["ErrorMsg"].(string)
  93. }
  94. // HasError returns true if error occurs in form validation.
  95. func (c *Context) HasError() bool {
  96. hasErr, ok := c.Data["HasError"]
  97. if !ok {
  98. return false
  99. }
  100. c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
  101. c.Data["Flash"] = c.Flash
  102. return hasErr.(bool)
  103. }
  104. // HasValue returns true if value of given name exists.
  105. func (c *Context) HasValue(name string) bool {
  106. _, ok := c.Data[name]
  107. return ok
  108. }
  109. // HTML responses template with given status.
  110. func (c *Context) HTML(status int, name string) {
  111. log.Trace("Template: %s", name)
  112. c.Context.HTML(status, name)
  113. }
  114. // Success responses template with status http.StatusOK.
  115. func (c *Context) Success(name string) {
  116. c.HTML(http.StatusOK, name)
  117. }
  118. // JSONSuccess responses JSON with status http.StatusOK.
  119. func (c *Context) JSONSuccess(data interface{}) {
  120. c.JSON(http.StatusOK, data)
  121. }
  122. // RawRedirect simply calls underlying Redirect method with no escape.
  123. func (c *Context) RawRedirect(location string, status ...int) {
  124. c.Context.Redirect(location, status...)
  125. }
  126. // Redirect responses redirection wtih given location and status.
  127. // It escapes special characters in the location string.
  128. func (c *Context) Redirect(location string, status ...int) {
  129. c.Context.Redirect(template.EscapePound(location), status...)
  130. }
  131. // SubURLRedirect responses redirection wtih given location and status.
  132. // It prepends setting.Server.Subpath to the location string.
  133. func (c *Context) SubURLRedirect(location string, status ...int) {
  134. c.Redirect(conf.Server.Subpath+location, status...)
  135. }
  136. // RenderWithErr used for page has form validation but need to prompt error to users.
  137. func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
  138. if f != nil {
  139. form.Assign(f, c.Data)
  140. }
  141. c.Flash.ErrorMsg = msg
  142. c.Data["Flash"] = c.Flash
  143. c.HTML(http.StatusOK, tpl)
  144. }
  145. // Handle handles and logs error by given status.
  146. func (c *Context) Handle(status int, msg string, err error) {
  147. switch status {
  148. case http.StatusNotFound:
  149. c.Data["Title"] = "Page Not Found"
  150. case http.StatusInternalServerError:
  151. c.Data["Title"] = "Internal Server Error"
  152. log.ErrorDepth(5, "%s: %v", msg, err)
  153. if !conf.IsProdMode() || (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(msg string, err error) {
  165. c.Handle(http.StatusInternalServerError, msg, 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(msg string, errck func(error) bool, err error) {
  171. if errck(err) {
  172. c.NotFound()
  173. return
  174. }
  175. c.ServerError(msg, err)
  176. }
  177. func (c *Context) HandleText(status int, msg string) {
  178. c.PlainText(status, []byte(msg))
  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: conf.Server.Subpath + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
  207. Repo: &Repository{
  208. PullRequest: &PullRequest{},
  209. },
  210. Org: &Organization{},
  211. }
  212. c.Data["Link"] = template.EscapePound(c.Link)
  213. c.Data["PageStartTime"] = time.Now()
  214. // Quick responses appropriate go-get meta with status 200
  215. // regardless of if user have access to the repository,
  216. // or the repository does not exist at all.
  217. // This is particular a workaround for "go get" command which does not respect
  218. // .netrc file.
  219. if c.Query("go-get") == "1" {
  220. ownerName := c.Params(":username")
  221. repoName := c.Params(":reponame")
  222. branchName := "master"
  223. owner, err := db.GetUserByName(ownerName)
  224. if err != nil {
  225. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  226. return
  227. }
  228. repo, err := db.GetRepositoryByName(owner.ID, repoName)
  229. if err == nil && len(repo.DefaultBranch) > 0 {
  230. branchName = repo.DefaultBranch
  231. }
  232. prefix := conf.Server.ExternalURL + path.Join(ownerName, repoName, "src", branchName)
  233. insecureFlag := ""
  234. if !strings.HasPrefix(conf.Server.ExternalURL, "https://") {
  235. insecureFlag = "--insecure "
  236. }
  237. c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
  238. <html>
  239. <head>
  240. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  241. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  242. </head>
  243. <body>
  244. go get {InsecureFlag}{GoGetImport}
  245. </body>
  246. </html>
  247. `, map[string]string{
  248. "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, repo.FullName()),
  249. "CloneLink": db.ComposeHTTPSCloneURL(ownerName, repoName),
  250. "GoDocDirectory": prefix + "{/dir}",
  251. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  252. "InsecureFlag": insecureFlag,
  253. })))
  254. return
  255. }
  256. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  257. c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  258. c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
  259. c.Header().Set("Access-Control-Max-Age", "3600")
  260. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
  261. }
  262. // Get user from session or header when possible
  263. c.User, c.IsBasicAuth, c.IsTokenAuth = auth.SignedInUser(c.Context, c.Session)
  264. if c.User != nil {
  265. c.IsLogged = true
  266. c.Data["IsLogged"] = c.IsLogged
  267. c.Data["LoggedUser"] = c.User
  268. c.Data["LoggedUserID"] = c.User.ID
  269. c.Data["LoggedUserName"] = c.User.Name
  270. c.Data["IsAdmin"] = c.User.IsAdmin
  271. } else {
  272. c.Data["LoggedUserID"] = 0
  273. c.Data["LoggedUserName"] = ""
  274. }
  275. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  276. if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
  277. if err := c.Req.ParseMultipartForm(conf.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  278. c.ServerError("ParseMultipartForm", err)
  279. return
  280. }
  281. }
  282. c.Data["CSRFToken"] = x.GetToken()
  283. c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
  284. log.Trace("Session ID: %s", sess.ID())
  285. log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
  286. c.Data["ShowRegistrationButton"] = !conf.Auth.DisableRegistration
  287. c.Data["ShowFooterBranding"] = conf.Other.ShowFooterBranding
  288. c.renderNoticeBanner()
  289. ctx.Map(c)
  290. }
  291. }