You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
9.9 KiB

10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
9 years ago
8 years ago
Add lang specific font stacks for CJK (#6007) * Add lang specific font stacks * Force font changes Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix icons Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix octicons and icons Signed-off-by: Andrew Thornton <art27@cantab.net> * Just override the semantic ui fonts only Signed-off-by: Andrew Thornton <art27@cantab.net> * Missed the headers... override them too * Missed some more semantic ui stuff * Fix PT Sans Signed-off-by: Andrew Thornton <art27@cantab.net> * More changes Signed-off-by: Andrew Thornton <art27@cantab.net> * Squashed commit of the following: commit 7d1679e9079541359869c9e677ba7412bfcc59f3 Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 13:53:49 2019 +0100 Remove missed YaHei leftover from _home.less commit 0079121ea91860a323ed4e5cc1a9c0d490d9cefd Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 12:03:54 2019 +0100 Fix overdone fixes (inherit, :lang) commit 62c919915928ec1db4731d547e95885f91a0618d Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 02:29:10 2019 +0100 Fix elements w/ explicit lang (language chooser) commit b3117587aa2eb8570d60bed583a11ee5565418be Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 20:17:26 2019 +0100 Fix textarea also (to match body) commit 81cedf2c3012c4dd05a7680782b4a98e1b947f67 Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 19:41:39 2019 +0100 Revert css temporarily to fix conflict commit 80ff82797f3203cbeaf866f22e961334e137df89 Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 19:15:30 2019 +0100 Tweak CJK, fix Yu Gothic, more monospace inherits commit 581dceb9a869646c2c486dabb925c88c2680d70c Author: Mike L <cl.jeremy@qq.com> Date: Mon Mar 11 13:09:26 2019 +0100 Add Lato for latin extd. & cyrillic, improve CJK * update stylesheet
5 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  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. "html"
  7. "html/template"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/util"
  20. "github.com/Unknwon/com"
  21. "github.com/go-macaron/cache"
  22. "github.com/go-macaron/csrf"
  23. "github.com/go-macaron/i18n"
  24. "github.com/go-macaron/session"
  25. "gopkg.in/macaron.v1"
  26. )
  27. // Context represents context of a request.
  28. type Context struct {
  29. *macaron.Context
  30. Cache cache.Cache
  31. csrf csrf.CSRF
  32. Flash *session.Flash
  33. Session session.Store
  34. Link string // current request URL
  35. EscapedLink string
  36. User *models.User
  37. IsSigned bool
  38. IsBasicAuth bool
  39. Repo *Repository
  40. Org *Organization
  41. }
  42. // IsUserSiteAdmin returns true if current user is a site admin
  43. func (ctx *Context) IsUserSiteAdmin() bool {
  44. return ctx.IsSigned && ctx.User.IsAdmin
  45. }
  46. // IsUserRepoOwner returns true if current user owns current repo
  47. func (ctx *Context) IsUserRepoOwner() bool {
  48. return ctx.Repo.IsOwner()
  49. }
  50. // IsUserRepoAdmin returns true if current user is admin in current repo
  51. func (ctx *Context) IsUserRepoAdmin() bool {
  52. return ctx.Repo.IsAdmin()
  53. }
  54. // IsUserRepoWriter returns true if current user has write privilege in current repo
  55. func (ctx *Context) IsUserRepoWriter(unitTypes []models.UnitType) bool {
  56. for _, unitType := range unitTypes {
  57. if ctx.Repo.CanWrite(unitType) {
  58. return true
  59. }
  60. }
  61. return false
  62. }
  63. // IsUserRepoReaderSpecific returns true if current user can read current repo's specific part
  64. func (ctx *Context) IsUserRepoReaderSpecific(unitType models.UnitType) bool {
  65. return ctx.Repo.CanRead(unitType)
  66. }
  67. // IsUserRepoReaderAny returns true if current user can read any part of current repo
  68. func (ctx *Context) IsUserRepoReaderAny() bool {
  69. return ctx.Repo.HasAccess()
  70. }
  71. // HasAPIError returns true if error occurs in form validation.
  72. func (ctx *Context) HasAPIError() bool {
  73. hasErr, ok := ctx.Data["HasError"]
  74. if !ok {
  75. return false
  76. }
  77. return hasErr.(bool)
  78. }
  79. // GetErrMsg returns error message
  80. func (ctx *Context) GetErrMsg() string {
  81. return ctx.Data["ErrorMsg"].(string)
  82. }
  83. // HasError returns true if error occurs in form validation.
  84. func (ctx *Context) HasError() bool {
  85. hasErr, ok := ctx.Data["HasError"]
  86. if !ok {
  87. return false
  88. }
  89. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  90. ctx.Data["Flash"] = ctx.Flash
  91. return hasErr.(bool)
  92. }
  93. // HasValue returns true if value of given name exists.
  94. func (ctx *Context) HasValue(name string) bool {
  95. _, ok := ctx.Data[name]
  96. return ok
  97. }
  98. // RedirectToFirst redirects to first not empty URL
  99. func (ctx *Context) RedirectToFirst(location ...string) {
  100. for _, loc := range location {
  101. if len(loc) == 0 {
  102. continue
  103. }
  104. u, err := url.Parse(loc)
  105. if err != nil || (u.Scheme != "" && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {
  106. continue
  107. }
  108. ctx.Redirect(loc)
  109. return
  110. }
  111. ctx.Redirect(setting.AppSubURL + "/")
  112. }
  113. // HTML calls Context.HTML and converts template name to string.
  114. func (ctx *Context) HTML(status int, name base.TplName) {
  115. log.Debug("Template: %s", name)
  116. ctx.Context.HTML(status, string(name))
  117. }
  118. // RenderWithErr used for page has form validation but need to prompt error to users.
  119. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  120. if form != nil {
  121. auth.AssignForm(form, ctx.Data)
  122. }
  123. ctx.Flash.ErrorMsg = msg
  124. ctx.Data["Flash"] = ctx.Flash
  125. ctx.HTML(200, tpl)
  126. }
  127. // NotFound displays a 404 (Not Found) page and prints the given error, if any.
  128. func (ctx *Context) NotFound(title string, err error) {
  129. ctx.notFoundInternal(title, err)
  130. }
  131. func (ctx *Context) notFoundInternal(title string, err error) {
  132. if err != nil {
  133. log.ErrorWithSkip(2, "%s: %v", title, err)
  134. if macaron.Env != macaron.PROD {
  135. ctx.Data["ErrorMsg"] = err
  136. }
  137. }
  138. ctx.Data["IsRepo"] = ctx.Repo.Repository != nil
  139. ctx.Data["Title"] = "Page Not Found"
  140. ctx.HTML(http.StatusNotFound, base.TplName("status/404"))
  141. }
  142. // ServerError displays a 500 (Internal Server Error) page and prints the given
  143. // error, if any.
  144. func (ctx *Context) ServerError(title string, err error) {
  145. ctx.serverErrorInternal(title, err)
  146. }
  147. func (ctx *Context) serverErrorInternal(title string, err error) {
  148. if err != nil {
  149. log.ErrorWithSkip(2, "%s: %v", title, err)
  150. if macaron.Env != macaron.PROD {
  151. ctx.Data["ErrorMsg"] = err
  152. }
  153. }
  154. ctx.Data["Title"] = "Internal Server Error"
  155. ctx.HTML(http.StatusInternalServerError, base.TplName("status/500"))
  156. }
  157. // NotFoundOrServerError use error check function to determine if the error
  158. // is about not found. It responses with 404 status code for not found error,
  159. // or error context description for logging purpose of 500 server error.
  160. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  161. if errck(err) {
  162. ctx.notFoundInternal(title, err)
  163. return
  164. }
  165. ctx.serverErrorInternal(title, err)
  166. }
  167. // HandleText handles HTTP status code
  168. func (ctx *Context) HandleText(status int, title string) {
  169. if (status/100 == 4) || (status/100 == 5) {
  170. log.Error("%s", title)
  171. }
  172. ctx.PlainText(status, []byte(title))
  173. }
  174. // ServeContent serves content to http request
  175. func (ctx *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. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  184. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  185. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  186. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  187. ctx.Resp.Header().Set("Expires", "0")
  188. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  189. ctx.Resp.Header().Set("Pragma", "public")
  190. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  191. }
  192. // Contexter initializes a classic context for a request.
  193. func Contexter() macaron.Handler {
  194. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  195. ctx := &Context{
  196. Context: c,
  197. Cache: cache,
  198. csrf: x,
  199. Flash: f,
  200. Session: sess,
  201. Link: setting.AppSubURL + strings.TrimSuffix(c.Req.URL.EscapedPath(), "/"),
  202. Repo: &Repository{
  203. PullRequest: &PullRequest{},
  204. },
  205. Org: &Organization{},
  206. }
  207. ctx.Data["Language"] = ctx.Locale.Language()
  208. c.Data["Link"] = ctx.Link
  209. ctx.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 ctx.Query("go-get") == "1" {
  216. ownerName := c.Params(":username")
  217. repoName := c.Params(":reponame")
  218. branchName := "master"
  219. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  220. if err == nil && len(repo.DefaultBranch) > 0 {
  221. branchName = repo.DefaultBranch
  222. }
  223. prefix := setting.AppURL + path.Join(url.PathEscape(ownerName), url.PathEscape(repoName), "src", "branch", util.PathEscapeSegments(branchName))
  224. appURL, _ := url.Parse(setting.AppURL)
  225. insecure := ""
  226. if appURL.Scheme == string(setting.HTTP) {
  227. insecure = "--insecure "
  228. }
  229. c.Header().Set("Content-Type", "text/html")
  230. c.WriteHeader(http.StatusOK)
  231. _, _ = c.Write([]byte(com.Expand(`<!doctype html>
  232. <html>
  233. <head>
  234. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  235. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  236. </head>
  237. <body>
  238. go get {Insecure}{GoGetImport}
  239. </body>
  240. </html>
  241. `, map[string]string{
  242. "GoGetImport": ComposeGoGetImport(ownerName, strings.TrimSuffix(repoName, ".git")),
  243. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  244. "GoDocDirectory": prefix + "{/dir}",
  245. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  246. "Insecure": insecure,
  247. })))
  248. return
  249. }
  250. // Get user from session if logged in.
  251. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  252. if ctx.User != nil {
  253. ctx.IsSigned = true
  254. ctx.Data["IsSigned"] = ctx.IsSigned
  255. ctx.Data["SignedUser"] = ctx.User
  256. ctx.Data["SignedUserID"] = ctx.User.ID
  257. ctx.Data["SignedUserName"] = ctx.User.Name
  258. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  259. } else {
  260. ctx.Data["SignedUserID"] = int64(0)
  261. ctx.Data["SignedUserName"] = ""
  262. }
  263. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  264. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  265. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  266. ctx.ServerError("ParseMultipartForm", err)
  267. return
  268. }
  269. }
  270. ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
  271. ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken())
  272. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  273. log.Debug("Session ID: %s", sess.ID())
  274. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  275. ctx.Data["IsLandingPageHome"] = setting.LandingPageURL == setting.LandingPageHome
  276. ctx.Data["IsLandingPageExplore"] = setting.LandingPageURL == setting.LandingPageExplore
  277. ctx.Data["IsLandingPageOrganizations"] = setting.LandingPageURL == setting.LandingPageOrganizations
  278. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  279. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  280. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  281. ctx.Data["EnableSwagger"] = setting.API.EnableSwagger
  282. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  283. c.Map(ctx)
  284. }
  285. }