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.8KB

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