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

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