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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. // 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. }