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

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