You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.go 19 kB

Add basic integration test infrastructure (and new endpoint `/api/v1/version` for testing it) (#741) * Implement '/api/v1/version' * Cleanup and various fixes * Enhance run.sh * Add install_test.go * Add parameter utils.Config for testing handlers * Re-organize TestVersion.go * Rename functions * handling process cleanup properly * Fix missing function renaming * Cleanup the 'retry' logic * Cleanup * Remove unneeded logging code * Logging messages tweaking * Logging message tweaking * Fix logging messages * Use 'const' instead of hardwired numbers * We don't really need retries anymore * Move constant ServerHttpPort to install_test.go * Restore mistakenly removed constant * Add required comments to make the linter happy. * Fix comments and naming to address linter's complaints * Detect Gitea executale version automatically * Remove tests/run.sh, `go test` suffices. * Make `make build` a prerequisite of `make test` * Do not sleep before trying * Speedup the server pinging loop * Use defined const instead of hardwired numbers * Remove redundant error handling * Use a dedicated target for running code.gitea.io/tests * Do not make 'test' depend on 'build' target * Rectify the excluded package list * Remove redundant 'exit 1' * Change the API to allow passing test.T to test handlers * Make testing.T an embedded field * Use assert.Equal to comparing results * Add copyright info * Parametrized logging output * Use tmpdir instead * Eliminate redundant casting * Remove unneeded variable * Fix last commit * Add missing copyright info * Replace fmt.Fprintf with fmt.Fprint * rename the xtest to integration-test * Use Symlink instead of hard-link for cross-device linking * Turn debugging logs on * Follow the existing framework for APIs * Output logs only if test.v is true * Re-order import statements * Enhance the error message * Fix comment which breaks the linter's rule * Rename 'integration-test' to 'e2e-test' for saving keystrokes * Add comment to avoid possible confusion * Rename tests -> integration-tests Also change back the Makefile to use `make integration-test`. * Use tests/integration for now * tests/integration -> integrations Slightly flattened directory hierarchy is better. * Update Makefile accordingly * Fix a missing change in Makefile * govendor update code.gitea.io/sdk/gitea * Fix comment of struct fields * Fix conditional nonsense * Fix missing updates regarding version string changes * Make variable naming more consistent * Check http status code * Rectify error messages
8 years ago
10 years ago
9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
10 years ago
10 years ago
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
7 years ago
8 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 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 v1 Gitea API.
  6. //
  7. // This documentation describes the Gitea API.
  8. //
  9. // Schemes: http, https
  10. // BasePath: /api/v1
  11. // Version: 1.1.1
  12. // License: MIT http://opensource.org/licenses/MIT
  13. //
  14. // Consumes:
  15. // - application/json
  16. // - text/plain
  17. //
  18. // Produces:
  19. // - application/json
  20. // - text/html
  21. //
  22. // Security:
  23. // - BasicAuth :
  24. // - Token :
  25. // - AccessToken :
  26. // - AuthorizationHeaderToken :
  27. // - SudoParam :
  28. // - SudoHeader :
  29. //
  30. // SecurityDefinitions:
  31. // BasicAuth:
  32. // type: basic
  33. // Token:
  34. // type: apiKey
  35. // name: token
  36. // in: query
  37. // AccessToken:
  38. // type: apiKey
  39. // name: access_token
  40. // in: query
  41. // AuthorizationHeaderToken:
  42. // type: apiKey
  43. // name: Authorization
  44. // in: header
  45. // SudoParam:
  46. // type: apiKey
  47. // name: sudo
  48. // in: query
  49. // description: Sudo API request as the user provided as the key. Admin privileges are required.
  50. // SudoHeader:
  51. // type: apiKey
  52. // name: Sudo
  53. // in: header
  54. // description: Sudo API request as the user provided as the key. Admin privileges are required.
  55. //
  56. // swagger:meta
  57. package v1
  58. import (
  59. "strings"
  60. "code.gitea.io/gitea/models"
  61. "code.gitea.io/gitea/modules/auth"
  62. "code.gitea.io/gitea/modules/context"
  63. "code.gitea.io/gitea/modules/log"
  64. "code.gitea.io/gitea/modules/setting"
  65. "code.gitea.io/gitea/routers/api/v1/admin"
  66. "code.gitea.io/gitea/routers/api/v1/misc"
  67. "code.gitea.io/gitea/routers/api/v1/org"
  68. "code.gitea.io/gitea/routers/api/v1/repo"
  69. _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
  70. "code.gitea.io/gitea/routers/api/v1/user"
  71. "code.gitea.io/gitea/routers/api/v1/utils"
  72. api "code.gitea.io/sdk/gitea"
  73. "github.com/go-macaron/binding"
  74. "gopkg.in/macaron.v1"
  75. )
  76. func sudo() macaron.Handler {
  77. return func(ctx *context.APIContext) {
  78. sudo := ctx.Query("sudo")
  79. if len(sudo) == 0 {
  80. sudo = ctx.Req.Header.Get("Sudo")
  81. }
  82. if len(sudo) > 0 {
  83. if ctx.User.IsAdmin {
  84. user, err := models.GetUserByName(sudo)
  85. if err != nil {
  86. if models.IsErrUserNotExist(err) {
  87. ctx.Status(404)
  88. } else {
  89. ctx.Error(500, "GetUserByName", err)
  90. }
  91. return
  92. }
  93. log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name)
  94. ctx.User = user
  95. } else {
  96. ctx.JSON(403, map[string]string{
  97. "message": "Only administrators allowed to sudo.",
  98. })
  99. return
  100. }
  101. }
  102. }
  103. }
  104. func repoAssignment() macaron.Handler {
  105. return func(ctx *context.APIContext) {
  106. userName := ctx.Params(":username")
  107. repoName := ctx.Params(":reponame")
  108. var (
  109. owner *models.User
  110. err error
  111. )
  112. // Check if the user is the same as the repository owner.
  113. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  114. owner = ctx.User
  115. } else {
  116. owner, err = models.GetUserByName(userName)
  117. if err != nil {
  118. if models.IsErrUserNotExist(err) {
  119. ctx.Status(404)
  120. } else {
  121. ctx.Error(500, "GetUserByName", err)
  122. }
  123. return
  124. }
  125. }
  126. ctx.Repo.Owner = owner
  127. // Get repository.
  128. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  129. if err != nil {
  130. if models.IsErrRepoNotExist(err) {
  131. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  132. if err == nil {
  133. context.RedirectToRepo(ctx.Context, redirectRepoID)
  134. } else if models.IsErrRepoRedirectNotExist(err) {
  135. ctx.Status(404)
  136. } else {
  137. ctx.Error(500, "LookupRepoRedirect", err)
  138. }
  139. } else {
  140. ctx.Error(500, "GetRepositoryByName", err)
  141. }
  142. return
  143. }
  144. repo.Owner = owner
  145. if ctx.IsSigned && ctx.User.IsAdmin {
  146. ctx.Repo.AccessMode = models.AccessModeOwner
  147. } else {
  148. mode, err := models.AccessLevel(utils.UserID(ctx), repo)
  149. if err != nil {
  150. ctx.Error(500, "AccessLevel", err)
  151. return
  152. }
  153. ctx.Repo.AccessMode = mode
  154. }
  155. if !ctx.Repo.HasAccess() {
  156. ctx.Status(404)
  157. return
  158. }
  159. ctx.Repo.Repository = repo
  160. }
  161. }
  162. // Contexter middleware already checks token for user sign in process.
  163. func reqToken() macaron.Handler {
  164. return func(ctx *context.APIContext) {
  165. if true == ctx.Data["IsApiToken"] {
  166. return
  167. }
  168. if ctx.IsSigned {
  169. ctx.RequireCSRF()
  170. return
  171. }
  172. ctx.Context.Error(401)
  173. }
  174. }
  175. func reqBasicAuth() macaron.Handler {
  176. return func(ctx *context.Context) {
  177. if !ctx.IsBasicAuth {
  178. ctx.Error(401)
  179. return
  180. }
  181. }
  182. }
  183. func reqAdmin() macaron.Handler {
  184. return func(ctx *context.Context) {
  185. if !ctx.IsSigned || !ctx.User.IsAdmin {
  186. ctx.Error(403)
  187. return
  188. }
  189. }
  190. }
  191. func reqRepoWriter() macaron.Handler {
  192. return func(ctx *context.Context) {
  193. if !ctx.Repo.IsWriter() {
  194. ctx.Error(403)
  195. return
  196. }
  197. }
  198. }
  199. func reqOrgMembership() macaron.Handler {
  200. return func(ctx *context.APIContext) {
  201. var orgID int64
  202. if ctx.Org.Organization != nil {
  203. orgID = ctx.Org.Organization.ID
  204. } else if ctx.Org.Team != nil {
  205. orgID = ctx.Org.Team.OrgID
  206. } else {
  207. ctx.Error(500, "", "reqOrgMembership: unprepared context")
  208. return
  209. }
  210. if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil {
  211. ctx.Error(500, "IsOrganizationMember", err)
  212. return
  213. } else if !isMember {
  214. if ctx.Org.Organization != nil {
  215. ctx.Error(403, "", "Must be an organization member")
  216. } else {
  217. ctx.Status(404)
  218. }
  219. return
  220. }
  221. }
  222. }
  223. func reqOrgOwnership() macaron.Handler {
  224. return func(ctx *context.APIContext) {
  225. var orgID int64
  226. if ctx.Org.Organization != nil {
  227. orgID = ctx.Org.Organization.ID
  228. } else if ctx.Org.Team != nil {
  229. orgID = ctx.Org.Team.OrgID
  230. } else {
  231. ctx.Error(500, "", "reqOrgOwnership: unprepared context")
  232. return
  233. }
  234. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  235. if err != nil {
  236. ctx.Error(500, "IsOrganizationOwner", err)
  237. } else if !isOwner {
  238. if ctx.Org.Organization != nil {
  239. ctx.Error(403, "", "Must be an organization owner")
  240. } else {
  241. ctx.Status(404)
  242. }
  243. return
  244. }
  245. }
  246. }
  247. func orgAssignment(args ...bool) macaron.Handler {
  248. var (
  249. assignOrg bool
  250. assignTeam bool
  251. )
  252. if len(args) > 0 {
  253. assignOrg = args[0]
  254. }
  255. if len(args) > 1 {
  256. assignTeam = args[1]
  257. }
  258. return func(ctx *context.APIContext) {
  259. ctx.Org = new(context.APIOrganization)
  260. var err error
  261. if assignOrg {
  262. ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname"))
  263. if err != nil {
  264. if models.IsErrOrgNotExist(err) {
  265. ctx.Status(404)
  266. } else {
  267. ctx.Error(500, "GetOrgByName", err)
  268. }
  269. return
  270. }
  271. }
  272. if assignTeam {
  273. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  274. if err != nil {
  275. if models.IsErrUserNotExist(err) {
  276. ctx.Status(404)
  277. } else {
  278. ctx.Error(500, "GetTeamById", err)
  279. }
  280. return
  281. }
  282. }
  283. }
  284. }
  285. func mustEnableIssues(ctx *context.APIContext) {
  286. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
  287. ctx.Status(404)
  288. return
  289. }
  290. }
  291. func mustAllowPulls(ctx *context.Context) {
  292. if !ctx.Repo.Repository.AllowsPulls() {
  293. ctx.Status(404)
  294. return
  295. }
  296. }
  297. func mustEnableIssuesOrPulls(ctx *context.Context) {
  298. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) &&
  299. !ctx.Repo.Repository.AllowsPulls() {
  300. ctx.Status(404)
  301. return
  302. }
  303. }
  304. func mustEnableUserHeatmap(ctx *context.Context) {
  305. if !setting.Service.EnableUserHeatmap {
  306. ctx.Status(404)
  307. return
  308. }
  309. }
  310. // RegisterRoutes registers all v1 APIs routes to web application.
  311. // FIXME: custom form error response
  312. func RegisterRoutes(m *macaron.Macaron) {
  313. bind := binding.Bind
  314. if setting.API.EnableSwagger {
  315. m.Get("/swagger", misc.Swagger) //Render V1 by default
  316. }
  317. m.Group("/v1", func() {
  318. // Miscellaneous
  319. if setting.API.EnableSwagger {
  320. m.Get("/swagger", misc.Swagger)
  321. }
  322. m.Get("/version", misc.Version)
  323. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  324. m.Post("/markdown/raw", misc.MarkdownRaw)
  325. // Users
  326. m.Group("/users", func() {
  327. m.Get("/search", user.Search)
  328. m.Group("/:username", func() {
  329. m.Get("", user.GetInfo)
  330. m.Get("/heatmap", mustEnableUserHeatmap, user.GetUserHeatmapData)
  331. m.Get("/repos", user.ListUserRepos)
  332. m.Group("/tokens", func() {
  333. m.Combo("").Get(user.ListAccessTokens).
  334. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  335. m.Combo("/:id").Delete(user.DeleteAccessToken)
  336. }, reqBasicAuth())
  337. })
  338. })
  339. m.Group("/users", func() {
  340. m.Group("/:username", func() {
  341. m.Get("/keys", user.ListPublicKeys)
  342. m.Get("/gpg_keys", user.ListGPGKeys)
  343. m.Get("/followers", user.ListFollowers)
  344. m.Group("/following", func() {
  345. m.Get("", user.ListFollowing)
  346. m.Get("/:target", user.CheckFollowing)
  347. })
  348. m.Get("/starred", user.GetStarredRepos)
  349. m.Get("/subscriptions", user.GetWatchedRepos)
  350. })
  351. }, reqToken())
  352. m.Group("/user", func() {
  353. m.Get("", user.GetAuthenticatedUser)
  354. m.Combo("/emails").Get(user.ListEmails).
  355. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  356. Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)
  357. m.Get("/followers", user.ListMyFollowers)
  358. m.Group("/following", func() {
  359. m.Get("", user.ListMyFollowing)
  360. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  361. })
  362. m.Group("/keys", func() {
  363. m.Combo("").Get(user.ListMyPublicKeys).
  364. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  365. m.Combo("/:id").Get(user.GetPublicKey).
  366. Delete(user.DeletePublicKey)
  367. })
  368. m.Group("/gpg_keys", func() {
  369. m.Combo("").Get(user.ListMyGPGKeys).
  370. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  371. m.Combo("/:id").Get(user.GetGPGKey).
  372. Delete(user.DeleteGPGKey)
  373. })
  374. m.Combo("/repos").Get(user.ListMyRepos).
  375. Post(bind(api.CreateRepoOption{}), repo.Create)
  376. m.Group("/starred", func() {
  377. m.Get("", user.GetMyStarredRepos)
  378. m.Group("/:username/:reponame", func() {
  379. m.Get("", user.IsStarring)
  380. m.Put("", user.Star)
  381. m.Delete("", user.Unstar)
  382. }, repoAssignment())
  383. })
  384. m.Get("/times", repo.ListMyTrackedTimes)
  385. m.Get("/subscriptions", user.GetMyWatchedRepos)
  386. }, reqToken())
  387. // Repositories
  388. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  389. m.Group("/repos", func() {
  390. m.Get("/search", repo.Search)
  391. })
  392. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  393. m.Group("/repos", func() {
  394. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  395. m.Group("/:username/:reponame", func() {
  396. m.Combo("").Get(repo.Get).Delete(reqToken(), repo.Delete)
  397. m.Group("/hooks", func() {
  398. m.Combo("").Get(repo.ListHooks).
  399. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  400. m.Group("/:id", func() {
  401. m.Combo("").Get(repo.GetHook).
  402. Patch(bind(api.EditHookOption{}), repo.EditHook).
  403. Delete(repo.DeleteHook)
  404. m.Post("/tests", context.RepoRef(), repo.TestHook)
  405. })
  406. }, reqToken(), reqRepoWriter())
  407. m.Group("/collaborators", func() {
  408. m.Get("", repo.ListCollaborators)
  409. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  410. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  411. Delete(repo.DeleteCollaborator)
  412. }, reqToken())
  413. m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), repo.GetRawFile)
  414. m.Get("/archive/*", repo.GetArchive)
  415. m.Combo("/forks").Get(repo.ListForks).
  416. Post(reqToken(), bind(api.CreateForkOption{}), repo.CreateFork)
  417. m.Group("/branches", func() {
  418. m.Get("", repo.ListBranches)
  419. m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
  420. })
  421. m.Group("/keys", func() {
  422. m.Combo("").Get(repo.ListDeployKeys).
  423. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  424. m.Combo("/:id").Get(repo.GetDeployKey).
  425. Delete(repo.DeleteDeploykey)
  426. }, reqToken(), reqRepoWriter())
  427. m.Group("/times", func() {
  428. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  429. m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)
  430. }, mustEnableIssues)
  431. m.Group("/issues", func() {
  432. m.Combo("").Get(repo.ListIssues).
  433. Post(reqToken(), bind(api.CreateIssueOption{}), repo.CreateIssue)
  434. m.Group("/comments", func() {
  435. m.Get("", repo.ListRepoIssueComments)
  436. m.Combo("/:id", reqToken()).
  437. Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  438. Delete(repo.DeleteIssueComment)
  439. })
  440. m.Group("/:index", func() {
  441. m.Combo("").Get(repo.GetIssue).
  442. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  443. m.Group("/comments", func() {
  444. m.Combo("").Get(repo.ListIssueComments).
  445. Post(reqToken(), bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  446. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  447. Delete(repo.DeleteIssueCommentDeprecated)
  448. })
  449. m.Group("/labels", func() {
  450. m.Combo("").Get(repo.ListIssueLabels).
  451. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  452. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  453. Delete(reqToken(), repo.ClearIssueLabels)
  454. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  455. })
  456. m.Group("/times", func() {
  457. m.Combo("").Get(repo.ListTrackedTimes).
  458. Post(reqToken(), bind(api.AddTimeOption{}), repo.AddTime)
  459. })
  460. m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  461. })
  462. }, mustEnableIssuesOrPulls)
  463. m.Group("/labels", func() {
  464. m.Combo("").Get(repo.ListLabels).
  465. Post(reqToken(), bind(api.CreateLabelOption{}), repo.CreateLabel)
  466. m.Combo("/:id").Get(repo.GetLabel).
  467. Patch(reqToken(), bind(api.EditLabelOption{}), repo.EditLabel).
  468. Delete(reqToken(), repo.DeleteLabel)
  469. })
  470. m.Group("/milestones", func() {
  471. m.Combo("").Get(repo.ListMilestones).
  472. Post(reqToken(), reqRepoWriter(), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  473. m.Combo("/:id").Get(repo.GetMilestone).
  474. Patch(reqToken(), reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  475. Delete(reqToken(), reqRepoWriter(), repo.DeleteMilestone)
  476. })
  477. m.Get("/stargazers", repo.ListStargazers)
  478. m.Get("/subscribers", repo.ListSubscribers)
  479. m.Group("/subscription", func() {
  480. m.Get("", user.IsWatching)
  481. m.Put("", reqToken(), user.Watch)
  482. m.Delete("", reqToken(), user.Unwatch)
  483. })
  484. m.Group("/releases", func() {
  485. m.Combo("").Get(repo.ListReleases).
  486. Post(reqToken(), reqRepoWriter(), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  487. m.Group("/:id", func() {
  488. m.Combo("").Get(repo.GetRelease).
  489. Patch(reqToken(), reqRepoWriter(), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease).
  490. Delete(reqToken(), reqRepoWriter(), repo.DeleteRelease)
  491. m.Group("/assets", func() {
  492. m.Combo("").Get(repo.ListReleaseAttachments).
  493. Post(reqToken(), reqRepoWriter(), repo.CreateReleaseAttachment)
  494. m.Combo("/:asset").Get(repo.GetReleaseAttachment).
  495. Patch(reqToken(), reqRepoWriter(), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  496. Delete(reqToken(), reqRepoWriter(), repo.DeleteReleaseAttachment)
  497. })
  498. })
  499. })
  500. m.Post("/mirror-sync", reqToken(), reqRepoWriter(), repo.MirrorSync)
  501. m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
  502. m.Group("/pulls", func() {
  503. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  504. Post(reqToken(), reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  505. m.Group("/:index", func() {
  506. m.Combo("").Get(repo.GetPullRequest).
  507. Patch(reqToken(), reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  508. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  509. Post(reqToken(), reqRepoWriter(), bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
  510. })
  511. }, mustAllowPulls, context.ReferencesGitRepo())
  512. m.Group("/statuses", func() {
  513. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  514. Post(reqToken(), reqRepoWriter(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  515. })
  516. m.Group("/commits/:ref", func() {
  517. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  518. m.Get("/statuses", repo.GetCommitStatusesByRef)
  519. })
  520. }, repoAssignment())
  521. })
  522. // Organizations
  523. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  524. m.Get("/users/:username/orgs", org.ListUserOrgs)
  525. m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
  526. m.Group("/orgs/:orgname", func() {
  527. m.Get("/repos", user.ListOrgRepos)
  528. m.Combo("").Get(org.Get).
  529. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit)
  530. m.Group("/members", func() {
  531. m.Get("", org.ListMembers)
  532. m.Combo("/:username").Get(org.IsMember).
  533. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  534. })
  535. m.Group("/public_members", func() {
  536. m.Get("", org.ListPublicMembers)
  537. m.Combo("/:username").Get(org.IsPublicMember).
  538. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  539. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  540. })
  541. m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
  542. Post(bind(api.CreateTeamOption{}), org.CreateTeam)
  543. m.Group("/hooks", func() {
  544. m.Combo("").Get(org.ListHooks).
  545. Post(bind(api.CreateHookOption{}), org.CreateHook)
  546. m.Combo("/:id").Get(org.GetHook).
  547. Patch(reqOrgOwnership(), bind(api.EditHookOption{}), org.EditHook).
  548. Delete(reqOrgOwnership(), org.DeleteHook)
  549. }, reqToken(), reqOrgMembership())
  550. }, orgAssignment(true))
  551. m.Group("/teams/:teamid", func() {
  552. m.Combo("").Get(org.GetTeam).
  553. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  554. Delete(reqOrgOwnership(), org.DeleteTeam)
  555. m.Group("/members", func() {
  556. m.Get("", org.GetTeamMembers)
  557. m.Combo("/:username").
  558. Put(reqOrgOwnership(), org.AddTeamMember).
  559. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  560. })
  561. m.Group("/repos", func() {
  562. m.Get("", org.GetTeamRepos)
  563. m.Combo("/:orgname/:reponame").
  564. Put(org.AddTeamRepository).
  565. Delete(org.RemoveTeamRepository)
  566. })
  567. }, orgAssignment(false, true), reqToken(), reqOrgMembership())
  568. m.Any("/*", func(ctx *context.Context) {
  569. ctx.Error(404)
  570. })
  571. m.Group("/admin", func() {
  572. m.Group("/users", func() {
  573. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  574. m.Group("/:username", func() {
  575. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  576. Delete(admin.DeleteUser)
  577. m.Group("/keys", func() {
  578. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  579. m.Delete("/:id", admin.DeleteUserPublicKey)
  580. })
  581. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  582. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  583. })
  584. })
  585. }, reqToken(), reqAdmin())
  586. m.Group("/topics", func() {
  587. m.Get("/search", repo.TopicSearch)
  588. })
  589. }, context.APIContexter(), sudo())
  590. }