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 5.3KB

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