context.go 9.4 KB

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