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.

194 lines
4.9 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 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
8 years ago
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "fmt"
  8. "net/url"
  9. "path"
  10. "strings"
  11. "github.com/go-macaron/csrf"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "gopkg.in/macaron.v1"
  18. )
  19. // APIContext is a specific macaron context for API service
  20. type APIContext struct {
  21. *Context
  22. Org *APIOrganization
  23. }
  24. // APIError is error format response
  25. // swagger:response error
  26. type APIError struct {
  27. Message string `json:"message"`
  28. URL string `json:"url"`
  29. }
  30. // APIValidationError is error format response related to input validation
  31. // swagger:response validationError
  32. type APIValidationError struct {
  33. Message string `json:"message"`
  34. URL string `json:"url"`
  35. }
  36. //APIEmpty is an empty response
  37. // swagger:response empty
  38. type APIEmpty struct{}
  39. //APIForbiddenError is a forbidden error response
  40. // swagger:response forbidden
  41. type APIForbiddenError struct {
  42. APIError
  43. }
  44. //APINotFound is a not found empty response
  45. // swagger:response notFound
  46. type APINotFound struct{}
  47. //APIRedirect is a redirect response
  48. // swagger:response redirect
  49. type APIRedirect struct{}
  50. // Error responses error message to client with given message.
  51. // If status is 500, also it prints error to log.
  52. func (ctx *APIContext) Error(status int, title string, obj interface{}) {
  53. var message string
  54. if err, ok := obj.(error); ok {
  55. message = err.Error()
  56. } else {
  57. message = obj.(string)
  58. }
  59. if status == 500 {
  60. log.Error("%s: %s", title, message)
  61. }
  62. ctx.JSON(status, APIError{
  63. Message: message,
  64. URL: base.DocURL,
  65. })
  66. }
  67. // SetLinkHeader sets pagination link header by given total number and page size.
  68. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  69. page := NewPagination(total, pageSize, ctx.QueryInt("page"), 0)
  70. paginater := page.Paginater
  71. links := make([]string, 0, 4)
  72. if paginater.HasNext() {
  73. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, ctx.Req.URL.Path[1:], paginater.Next()))
  74. }
  75. if !paginater.IsLast() {
  76. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, ctx.Req.URL.Path[1:], paginater.TotalPages()))
  77. }
  78. if !paginater.IsFirst() {
  79. links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, ctx.Req.URL.Path[1:]))
  80. }
  81. if paginater.HasPrevious() {
  82. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, ctx.Req.URL.Path[1:], paginater.Previous()))
  83. }
  84. if len(links) > 0 {
  85. ctx.Header().Set("Link", strings.Join(links, ","))
  86. }
  87. }
  88. // RequireCSRF requires a validated a CSRF token
  89. func (ctx *APIContext) RequireCSRF() {
  90. headerToken := ctx.Req.Header.Get(ctx.csrf.GetHeaderName())
  91. formValueToken := ctx.Req.FormValue(ctx.csrf.GetFormName())
  92. if len(headerToken) > 0 || len(formValueToken) > 0 {
  93. csrf.Validate(ctx.Context.Context, ctx.csrf)
  94. } else {
  95. ctx.Context.Error(401)
  96. }
  97. }
  98. // CheckForOTP validateds OTP
  99. func (ctx *APIContext) CheckForOTP() {
  100. otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
  101. twofa, err := models.GetTwoFactorByUID(ctx.Context.User.ID)
  102. if err != nil {
  103. if models.IsErrTwoFactorNotEnrolled(err) {
  104. return // No 2FA enrollment for this user
  105. }
  106. ctx.Context.Error(500)
  107. return
  108. }
  109. ok, err := twofa.ValidateTOTP(otpHeader)
  110. if err != nil {
  111. ctx.Context.Error(500)
  112. return
  113. }
  114. if !ok {
  115. ctx.Context.Error(401)
  116. return
  117. }
  118. }
  119. // APIContexter returns apicontext as macaron middleware
  120. func APIContexter() macaron.Handler {
  121. return func(c *Context) {
  122. ctx := &APIContext{
  123. Context: c,
  124. }
  125. c.Map(ctx)
  126. }
  127. }
  128. // ReferencesGitRepo injects the GitRepo into the Context
  129. func ReferencesGitRepo(allowEmpty bool) macaron.Handler {
  130. return func(ctx *APIContext) {
  131. // Empty repository does not have reference information.
  132. if !allowEmpty && ctx.Repo.Repository.IsEmpty {
  133. return
  134. }
  135. // For API calls.
  136. if ctx.Repo.GitRepo == nil {
  137. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  138. gitRepo, err := git.OpenRepository(repoPath)
  139. if err != nil {
  140. ctx.Error(500, "RepoRef Invalid repo "+repoPath, err)
  141. return
  142. }
  143. ctx.Repo.GitRepo = gitRepo
  144. }
  145. }
  146. }
  147. // NotFound handles 404s for APIContext
  148. // String will replace message, errors will be added to a slice
  149. func (ctx *APIContext) NotFound(objs ...interface{}) {
  150. var message = "Not Found"
  151. var errors []string
  152. for _, obj := range objs {
  153. if err, ok := obj.(error); ok {
  154. errors = append(errors, err.Error())
  155. } else {
  156. message = obj.(string)
  157. }
  158. }
  159. u, err := url.Parse(setting.AppURL)
  160. if err != nil {
  161. ctx.Error(500, "Invalid AppURL", err)
  162. return
  163. }
  164. u.Path = path.Join(u.Path, "api", "swagger")
  165. ctx.JSON(404, map[string]interface{}{
  166. "message": message,
  167. "documentation_url": u.String(),
  168. "errors": errors,
  169. })
  170. }