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.

api.go 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. "github.com/Unknwon/paginater"
  18. macaron "gopkg.in/macaron.v1"
  19. )
  20. // APIContext is a specific macaron context for API service
  21. type APIContext struct {
  22. *Context
  23. Org *APIOrganization
  24. }
  25. // APIError is error format response
  26. // swagger:response error
  27. type APIError struct {
  28. Message string `json:"message"`
  29. URL string `json:"url"`
  30. }
  31. // APIValidationError is error format response related to input validation
  32. // swagger:response validationError
  33. type APIValidationError struct {
  34. Message string `json:"message"`
  35. URL string `json:"url"`
  36. }
  37. //APIEmpty is an empty response
  38. // swagger:response empty
  39. type APIEmpty struct{}
  40. //APIForbiddenError is a forbidden error response
  41. // swagger:response forbidden
  42. type APIForbiddenError struct {
  43. APIError
  44. }
  45. //APINotFound is a not found empty response
  46. // swagger:response notFound
  47. type APINotFound struct{}
  48. //APIRedirect is a redirect response
  49. // swagger:response redirect
  50. type APIRedirect struct{}
  51. // Error responses error message to client with given message.
  52. // If status is 500, also it prints error to log.
  53. func (ctx *APIContext) Error(status int, title string, obj interface{}) {
  54. var message string
  55. if err, ok := obj.(error); ok {
  56. message = err.Error()
  57. } else {
  58. message = obj.(string)
  59. }
  60. if status == 500 {
  61. log.Error("%s: %s", title, message)
  62. }
  63. ctx.JSON(status, APIError{
  64. Message: message,
  65. URL: base.DocURL,
  66. })
  67. }
  68. // SetLinkHeader sets pagination link header by given total number and page size.
  69. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  70. page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0)
  71. links := make([]string, 0, 4)
  72. if page.HasNext() {
  73. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Next()))
  74. }
  75. if !page.IsLast() {
  76. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, ctx.Req.URL.Path[1:], page.TotalPages()))
  77. }
  78. if !page.IsFirst() {
  79. links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, ctx.Req.URL.Path[1:]))
  80. }
  81. if page.HasPrevious() {
  82. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, ctx.Req.URL.Path[1:], page.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. // APIContexter returns apicontext as macaron middleware
  99. func APIContexter() macaron.Handler {
  100. return func(c *Context) {
  101. ctx := &APIContext{
  102. Context: c,
  103. }
  104. c.Map(ctx)
  105. }
  106. }
  107. // ReferencesGitRepo injects the GitRepo into the Context
  108. func ReferencesGitRepo(allowEmpty bool) macaron.Handler {
  109. return func(ctx *APIContext) {
  110. // Empty repository does not have reference information.
  111. if !allowEmpty && ctx.Repo.Repository.IsEmpty {
  112. return
  113. }
  114. // For API calls.
  115. if ctx.Repo.GitRepo == nil {
  116. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  117. gitRepo, err := git.OpenRepository(repoPath)
  118. if err != nil {
  119. ctx.Error(500, "RepoRef Invalid repo "+repoPath, err)
  120. return
  121. }
  122. ctx.Repo.GitRepo = gitRepo
  123. }
  124. }
  125. }
  126. // NotFound handles 404s for APIContext
  127. // String will replace message, errors will be added to a slice
  128. func (ctx *APIContext) NotFound(objs ...interface{}) {
  129. var message = "Not Found"
  130. var errors []string
  131. for _, obj := range objs {
  132. if err, ok := obj.(error); ok {
  133. errors = append(errors, err.Error())
  134. } else {
  135. message = obj.(string)
  136. }
  137. }
  138. u, err := url.Parse(setting.AppURL)
  139. if err != nil {
  140. ctx.Error(500, "Invalid AppURL", err)
  141. return
  142. }
  143. u.Path = path.Join(u.Path, "api", "swagger")
  144. ctx.JSON(404, map[string]interface{}{
  145. "message": message,
  146. "documentation_url": u.String(),
  147. "errors": errors,
  148. })
  149. }