Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. if macaron.Env == macaron.PROD {
  67. message = ""
  68. }
  69. }
  70. ctx.JSON(status, APIError{
  71. Message: message,
  72. URL: setting.API.SwaggerURL,
  73. })
  74. }
  75. // InternalServerError responds with an error message to the client with the error as a message
  76. // and the file and line of the caller.
  77. func (ctx *APIContext) InternalServerError(err error) {
  78. log.ErrorWithSkip(1, "InternalServerError: %v", err)
  79. var message string
  80. if macaron.Env != macaron.PROD {
  81. message = err.Error()
  82. }
  83. ctx.JSON(http.StatusInternalServerError, APIError{
  84. Message: message,
  85. URL: setting.API.SwaggerURL,
  86. })
  87. }
  88. func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
  89. page := NewPagination(total, pageSize, curPage, 0)
  90. paginater := page.Paginater
  91. links := make([]string, 0, 4)
  92. if paginater.HasNext() {
  93. u := *curURL
  94. queries := u.Query()
  95. queries.Set("page", fmt.Sprintf("%d", paginater.Next()))
  96. u.RawQuery = queries.Encode()
  97. links = append(links, fmt.Sprintf("<%s%s>; rel=\"next\"", setting.AppURL, u.RequestURI()[1:]))
  98. }
  99. if !paginater.IsLast() {
  100. u := *curURL
  101. queries := u.Query()
  102. queries.Set("page", fmt.Sprintf("%d", paginater.TotalPages()))
  103. u.RawQuery = queries.Encode()
  104. links = append(links, fmt.Sprintf("<%s%s>; rel=\"last\"", setting.AppURL, u.RequestURI()[1:]))
  105. }
  106. if !paginater.IsFirst() {
  107. u := *curURL
  108. queries := u.Query()
  109. queries.Set("page", "1")
  110. u.RawQuery = queries.Encode()
  111. links = append(links, fmt.Sprintf("<%s%s>; rel=\"first\"", setting.AppURL, u.RequestURI()[1:]))
  112. }
  113. if paginater.HasPrevious() {
  114. u := *curURL
  115. queries := u.Query()
  116. queries.Set("page", fmt.Sprintf("%d", paginater.Previous()))
  117. u.RawQuery = queries.Encode()
  118. links = append(links, fmt.Sprintf("<%s%s>; rel=\"prev\"", setting.AppURL, u.RequestURI()[1:]))
  119. }
  120. return links
  121. }
  122. // SetLinkHeader sets pagination link header by given total number and page size.
  123. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  124. links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.QueryInt("page"))
  125. if len(links) > 0 {
  126. ctx.Header().Set("Link", strings.Join(links, ","))
  127. }
  128. }
  129. // RequireCSRF requires a validated a CSRF token
  130. func (ctx *APIContext) RequireCSRF() {
  131. headerToken := ctx.Req.Header.Get(ctx.csrf.GetHeaderName())
  132. formValueToken := ctx.Req.FormValue(ctx.csrf.GetFormName())
  133. if len(headerToken) > 0 || len(formValueToken) > 0 {
  134. csrf.Validate(ctx.Context.Context, ctx.csrf)
  135. } else {
  136. ctx.Context.Error(401)
  137. }
  138. }
  139. // CheckForOTP validateds OTP
  140. func (ctx *APIContext) CheckForOTP() {
  141. otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
  142. twofa, err := models.GetTwoFactorByUID(ctx.Context.User.ID)
  143. if err != nil {
  144. if models.IsErrTwoFactorNotEnrolled(err) {
  145. return // No 2FA enrollment for this user
  146. }
  147. ctx.Context.Error(500)
  148. return
  149. }
  150. ok, err := twofa.ValidateTOTP(otpHeader)
  151. if err != nil {
  152. ctx.Context.Error(500)
  153. return
  154. }
  155. if !ok {
  156. ctx.Context.Error(401)
  157. return
  158. }
  159. }
  160. // APIContexter returns apicontext as macaron middleware
  161. func APIContexter() macaron.Handler {
  162. return func(c *Context) {
  163. ctx := &APIContext{
  164. Context: c,
  165. }
  166. c.Map(ctx)
  167. }
  168. }
  169. // ReferencesGitRepo injects the GitRepo into the Context
  170. func ReferencesGitRepo(allowEmpty bool) macaron.Handler {
  171. return func(ctx *APIContext) {
  172. // Empty repository does not have reference information.
  173. if !allowEmpty && ctx.Repo.Repository.IsEmpty {
  174. return
  175. }
  176. // For API calls.
  177. if ctx.Repo.GitRepo == nil {
  178. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  179. gitRepo, err := git.OpenRepository(repoPath)
  180. if err != nil {
  181. ctx.Error(500, "RepoRef Invalid repo "+repoPath, err)
  182. return
  183. }
  184. ctx.Repo.GitRepo = gitRepo
  185. // We opened it, we should close it
  186. defer func() {
  187. // If it's been set to nil then assume someone else has closed it.
  188. if ctx.Repo.GitRepo != nil {
  189. ctx.Repo.GitRepo.Close()
  190. }
  191. }()
  192. }
  193. ctx.Next()
  194. }
  195. }
  196. // NotFound handles 404s for APIContext
  197. // String will replace message, errors will be added to a slice
  198. func (ctx *APIContext) NotFound(objs ...interface{}) {
  199. var message = "Not Found"
  200. var errors []string
  201. for _, obj := range objs {
  202. // Ignore nil
  203. if obj == nil {
  204. continue
  205. }
  206. if err, ok := obj.(error); ok {
  207. errors = append(errors, err.Error())
  208. } else {
  209. message = obj.(string)
  210. }
  211. }
  212. ctx.JSON(404, map[string]interface{}{
  213. "message": message,
  214. "documentation_url": setting.API.SwaggerURL,
  215. "errors": errors,
  216. })
  217. }