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 18 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
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>
7 years ago
9 years ago
9 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>
7 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>
7 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package v1 Gitea API.
  5. //
  6. // This documentation describes the Gitea API.
  7. //
  8. // Schemes: http, https
  9. // BasePath: /api/v1
  10. // Version: 1.1.1
  11. // License: MIT http://opensource.org/licenses/MIT
  12. //
  13. // Consumes:
  14. // - application/json
  15. // - text/plain
  16. //
  17. // Produces:
  18. // - application/json
  19. // - text/html
  20. //
  21. // Security:
  22. // - BasicAuth :
  23. // - Token :
  24. // - AccessToken :
  25. // - AuthorizationHeaderToken :
  26. //
  27. // SecurityDefinitions:
  28. // BasicAuth:
  29. // type: basic
  30. // Token:
  31. // type: apiKey
  32. // name: token
  33. // in: query
  34. // AccessToken:
  35. // type: apiKey
  36. // name: access_token
  37. // in: query
  38. // AuthorizationHeaderToken:
  39. // type: apiKey
  40. // name: Authorization
  41. // in: header
  42. //
  43. // swagger:meta
  44. package v1
  45. import (
  46. "strings"
  47. "code.gitea.io/gitea/models"
  48. "code.gitea.io/gitea/modules/auth"
  49. "code.gitea.io/gitea/modules/context"
  50. "code.gitea.io/gitea/modules/setting"
  51. "code.gitea.io/gitea/routers/api/v1/admin"
  52. "code.gitea.io/gitea/routers/api/v1/misc"
  53. "code.gitea.io/gitea/routers/api/v1/org"
  54. "code.gitea.io/gitea/routers/api/v1/repo"
  55. _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
  56. "code.gitea.io/gitea/routers/api/v1/user"
  57. "code.gitea.io/gitea/routers/api/v1/utils"
  58. api "code.gitea.io/sdk/gitea"
  59. "github.com/go-macaron/binding"
  60. "gopkg.in/macaron.v1"
  61. )
  62. func repoAssignment() macaron.Handler {
  63. return func(ctx *context.APIContext) {
  64. userName := ctx.Params(":username")
  65. repoName := ctx.Params(":reponame")
  66. var (
  67. owner *models.User
  68. err error
  69. )
  70. // Check if the user is the same as the repository owner.
  71. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  72. owner = ctx.User
  73. } else {
  74. owner, err = models.GetUserByName(userName)
  75. if err != nil {
  76. if models.IsErrUserNotExist(err) {
  77. ctx.Status(404)
  78. } else {
  79. ctx.Error(500, "GetUserByName", err)
  80. }
  81. return
  82. }
  83. }
  84. ctx.Repo.Owner = owner
  85. // Get repository.
  86. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  87. if err != nil {
  88. if models.IsErrRepoNotExist(err) {
  89. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  90. if err == nil {
  91. context.RedirectToRepo(ctx.Context, redirectRepoID)
  92. } else if models.IsErrRepoRedirectNotExist(err) {
  93. ctx.Status(404)
  94. } else {
  95. ctx.Error(500, "LookupRepoRedirect", err)
  96. }
  97. } else {
  98. ctx.Error(500, "GetRepositoryByName", err)
  99. }
  100. return
  101. }
  102. repo.Owner = owner
  103. if ctx.IsSigned && ctx.User.IsAdmin {
  104. ctx.Repo.AccessMode = models.AccessModeOwner
  105. } else {
  106. mode, err := models.AccessLevel(utils.UserID(ctx), repo)
  107. if err != nil {
  108. ctx.Error(500, "AccessLevel", err)
  109. return
  110. }
  111. ctx.Repo.AccessMode = mode
  112. }
  113. if !ctx.Repo.HasAccess() {
  114. ctx.Status(404)
  115. return
  116. }
  117. ctx.Repo.Repository = repo
  118. }
  119. }
  120. // Contexter middleware already checks token for user sign in process.
  121. func reqToken() macaron.Handler {
  122. return func(ctx *context.Context) {
  123. if !ctx.IsSigned {
  124. ctx.Error(401)
  125. return
  126. }
  127. }
  128. }
  129. func reqBasicAuth() macaron.Handler {
  130. return func(ctx *context.Context) {
  131. if !ctx.IsBasicAuth {
  132. ctx.Error(401)
  133. return
  134. }
  135. }
  136. }
  137. func reqAdmin() macaron.Handler {
  138. return func(ctx *context.Context) {
  139. if !ctx.IsSigned || !ctx.User.IsAdmin {
  140. ctx.Error(403)
  141. return
  142. }
  143. }
  144. }
  145. func reqRepoWriter() macaron.Handler {
  146. return func(ctx *context.Context) {
  147. if !ctx.Repo.IsWriter() {
  148. ctx.Error(403)
  149. return
  150. }
  151. }
  152. }
  153. func reqOrgMembership() macaron.Handler {
  154. return func(ctx *context.APIContext) {
  155. var orgID int64
  156. if ctx.Org.Organization != nil {
  157. orgID = ctx.Org.Organization.ID
  158. } else if ctx.Org.Team != nil {
  159. orgID = ctx.Org.Team.OrgID
  160. } else {
  161. ctx.Error(500, "", "reqOrgMembership: unprepared context")
  162. return
  163. }
  164. if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil {
  165. ctx.Error(500, "IsOrganizationMember", err)
  166. return
  167. } else if !isMember {
  168. if ctx.Org.Organization != nil {
  169. ctx.Error(403, "", "Must be an organization member")
  170. } else {
  171. ctx.Status(404)
  172. }
  173. return
  174. }
  175. }
  176. }
  177. func reqOrgOwnership() macaron.Handler {
  178. return func(ctx *context.APIContext) {
  179. var orgID int64
  180. if ctx.Org.Organization != nil {
  181. orgID = ctx.Org.Organization.ID
  182. } else if ctx.Org.Team != nil {
  183. orgID = ctx.Org.Team.OrgID
  184. } else {
  185. ctx.Error(500, "", "reqOrgOwnership: unprepared context")
  186. return
  187. }
  188. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  189. if err != nil {
  190. ctx.Error(500, "IsOrganizationOwner", err)
  191. } else if !isOwner {
  192. if ctx.Org.Organization != nil {
  193. ctx.Error(403, "", "Must be an organization owner")
  194. } else {
  195. ctx.Status(404)
  196. }
  197. return
  198. }
  199. }
  200. }
  201. func orgAssignment(args ...bool) macaron.Handler {
  202. var (
  203. assignOrg bool
  204. assignTeam bool
  205. )
  206. if len(args) > 0 {
  207. assignOrg = args[0]
  208. }
  209. if len(args) > 1 {
  210. assignTeam = args[1]
  211. }
  212. return func(ctx *context.APIContext) {
  213. ctx.Org = new(context.APIOrganization)
  214. var err error
  215. if assignOrg {
  216. ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname"))
  217. if err != nil {
  218. if models.IsErrOrgNotExist(err) {
  219. ctx.Status(404)
  220. } else {
  221. ctx.Error(500, "GetOrgByName", err)
  222. }
  223. return
  224. }
  225. }
  226. if assignTeam {
  227. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  228. if err != nil {
  229. if models.IsErrUserNotExist(err) {
  230. ctx.Status(404)
  231. } else {
  232. ctx.Error(500, "GetTeamById", err)
  233. }
  234. return
  235. }
  236. }
  237. }
  238. }
  239. func mustEnableIssues(ctx *context.APIContext) {
  240. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
  241. ctx.Status(404)
  242. return
  243. }
  244. }
  245. func mustAllowPulls(ctx *context.Context) {
  246. if !ctx.Repo.Repository.AllowsPulls() {
  247. ctx.Status(404)
  248. return
  249. }
  250. }
  251. func mustEnableIssuesOrPulls(ctx *context.Context) {
  252. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) &&
  253. !ctx.Repo.Repository.AllowsPulls() {
  254. ctx.Status(404)
  255. return
  256. }
  257. }
  258. // RegisterRoutes registers all v1 APIs routes to web application.
  259. // FIXME: custom form error response
  260. func RegisterRoutes(m *macaron.Macaron) {
  261. bind := binding.Bind
  262. if setting.API.EnableSwagger {
  263. m.Get("/swagger", misc.Swagger) //Render V1 by default
  264. }
  265. m.Group("/v1", func() {
  266. // Miscellaneous
  267. if setting.API.EnableSwagger {
  268. m.Get("/swagger", misc.Swagger)
  269. }
  270. m.Get("/version", misc.Version)
  271. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  272. m.Post("/markdown/raw", misc.MarkdownRaw)
  273. // Users
  274. m.Group("/users", func() {
  275. m.Get("/search", user.Search)
  276. m.Group("/:username", func() {
  277. m.Get("", user.GetInfo)
  278. m.Get("/repos", user.ListUserRepos)
  279. m.Group("/tokens", func() {
  280. m.Combo("").Get(user.ListAccessTokens).
  281. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  282. m.Combo("/:id").Delete(user.DeleteAccessToken)
  283. }, reqBasicAuth())
  284. })
  285. })
  286. m.Group("/users", func() {
  287. m.Group("/:username", func() {
  288. m.Get("/keys", user.ListPublicKeys)
  289. m.Get("/gpg_keys", user.ListGPGKeys)
  290. m.Get("/followers", user.ListFollowers)
  291. m.Group("/following", func() {
  292. m.Get("", user.ListFollowing)
  293. m.Get("/:target", user.CheckFollowing)
  294. })
  295. m.Get("/starred", user.GetStarredRepos)
  296. m.Get("/subscriptions", user.GetWatchedRepos)
  297. })
  298. }, reqToken())
  299. m.Group("/user", func() {
  300. m.Get("", user.GetAuthenticatedUser)
  301. m.Combo("/emails").Get(user.ListEmails).
  302. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  303. Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)
  304. m.Get("/followers", user.ListMyFollowers)
  305. m.Group("/following", func() {
  306. m.Get("", user.ListMyFollowing)
  307. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  308. })
  309. m.Group("/keys", func() {
  310. m.Combo("").Get(user.ListMyPublicKeys).
  311. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  312. m.Combo("/:id").Get(user.GetPublicKey).
  313. Delete(user.DeletePublicKey)
  314. })
  315. m.Group("/gpg_keys", func() {
  316. m.Combo("").Get(user.ListMyGPGKeys).
  317. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  318. m.Combo("/:id").Get(user.GetGPGKey).
  319. Delete(user.DeleteGPGKey)
  320. })
  321. m.Combo("/repos").Get(user.ListMyRepos).
  322. Post(bind(api.CreateRepoOption{}), repo.Create)
  323. m.Group("/starred", func() {
  324. m.Get("", user.GetMyStarredRepos)
  325. m.Group("/:username/:reponame", func() {
  326. m.Get("", user.IsStarring)
  327. m.Put("", user.Star)
  328. m.Delete("", user.Unstar)
  329. }, repoAssignment())
  330. })
  331. m.Get("/times", repo.ListMyTrackedTimes)
  332. m.Get("/subscriptions", user.GetMyWatchedRepos)
  333. }, reqToken())
  334. // Repositories
  335. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  336. m.Group("/repos", func() {
  337. m.Get("/search", repo.Search)
  338. })
  339. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  340. m.Group("/repos", func() {
  341. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  342. m.Group("/:username/:reponame", func() {
  343. m.Combo("").Get(repo.Get).Delete(reqToken(), repo.Delete)
  344. m.Group("/hooks", func() {
  345. m.Combo("").Get(repo.ListHooks).
  346. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  347. m.Group("/:id", func() {
  348. m.Combo("").Get(repo.GetHook).
  349. Patch(bind(api.EditHookOption{}), repo.EditHook).
  350. Delete(repo.DeleteHook)
  351. m.Post("/tests", context.RepoRef(), repo.TestHook)
  352. })
  353. }, reqToken(), reqRepoWriter())
  354. m.Group("/collaborators", func() {
  355. m.Get("", repo.ListCollaborators)
  356. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  357. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  358. Delete(repo.DeleteCollaborator)
  359. }, reqToken())
  360. m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), repo.GetRawFile)
  361. m.Get("/archive/*", repo.GetArchive)
  362. m.Combo("/forks").Get(repo.ListForks).
  363. Post(reqToken(), bind(api.CreateForkOption{}), repo.CreateFork)
  364. m.Group("/branches", func() {
  365. m.Get("", repo.ListBranches)
  366. m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
  367. })
  368. m.Group("/keys", func() {
  369. m.Combo("").Get(repo.ListDeployKeys).
  370. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  371. m.Combo("/:id").Get(repo.GetDeployKey).
  372. Delete(repo.DeleteDeploykey)
  373. }, reqToken(), reqRepoWriter())
  374. m.Group("/times", func() {
  375. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  376. m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)
  377. }, mustEnableIssues)
  378. m.Group("/issues", func() {
  379. m.Combo("").Get(repo.ListIssues).
  380. Post(reqToken(), bind(api.CreateIssueOption{}), repo.CreateIssue)
  381. m.Group("/comments", func() {
  382. m.Get("", repo.ListRepoIssueComments)
  383. m.Combo("/:id", reqToken()).
  384. Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  385. Delete(repo.DeleteIssueComment)
  386. })
  387. m.Group("/:index", func() {
  388. m.Combo("").Get(repo.GetIssue).
  389. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  390. m.Group("/comments", func() {
  391. m.Combo("").Get(repo.ListIssueComments).
  392. Post(reqToken(), bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  393. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  394. Delete(repo.DeleteIssueCommentDeprecated)
  395. })
  396. m.Group("/labels", func() {
  397. m.Combo("").Get(repo.ListIssueLabels).
  398. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  399. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  400. Delete(reqToken(), repo.ClearIssueLabels)
  401. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  402. })
  403. m.Group("/times", func() {
  404. m.Combo("").Get(repo.ListTrackedTimes).
  405. Post(reqToken(), bind(api.AddTimeOption{}), repo.AddTime)
  406. })
  407. m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  408. })
  409. }, mustEnableIssuesOrPulls)
  410. m.Group("/labels", func() {
  411. m.Combo("").Get(repo.ListLabels).
  412. Post(reqToken(), bind(api.CreateLabelOption{}), repo.CreateLabel)
  413. m.Combo("/:id").Get(repo.GetLabel).
  414. Patch(reqToken(), bind(api.EditLabelOption{}), repo.EditLabel).
  415. Delete(reqToken(), repo.DeleteLabel)
  416. })
  417. m.Group("/milestones", func() {
  418. m.Combo("").Get(repo.ListMilestones).
  419. Post(reqToken(), reqRepoWriter(), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  420. m.Combo("/:id").Get(repo.GetMilestone).
  421. Patch(reqToken(), reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  422. Delete(reqToken(), reqRepoWriter(), repo.DeleteMilestone)
  423. })
  424. m.Get("/stargazers", repo.ListStargazers)
  425. m.Get("/subscribers", repo.ListSubscribers)
  426. m.Group("/subscription", func() {
  427. m.Get("", user.IsWatching)
  428. m.Put("", reqToken(), user.Watch)
  429. m.Delete("", reqToken(), user.Unwatch)
  430. })
  431. m.Group("/releases", func() {
  432. m.Combo("").Get(repo.ListReleases).
  433. Post(reqToken(), reqRepoWriter(), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  434. m.Group("/:id", func() {
  435. m.Combo("").Get(repo.GetRelease).
  436. Patch(reqToken(), reqRepoWriter(), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease).
  437. Delete(reqToken(), reqRepoWriter(), repo.DeleteRelease)
  438. m.Group("/assets", func() {
  439. m.Combo("").Get(repo.ListReleaseAttachments).
  440. Post(reqToken(), reqRepoWriter(), repo.CreateReleaseAttachment)
  441. m.Combo("/:asset").Get(repo.GetReleaseAttachment).
  442. Patch(reqToken(), reqRepoWriter(), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  443. Delete(reqToken(), reqRepoWriter(), repo.DeleteReleaseAttachment)
  444. })
  445. })
  446. })
  447. m.Post("/mirror-sync", reqToken(), reqRepoWriter(), repo.MirrorSync)
  448. m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
  449. m.Group("/pulls", func() {
  450. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  451. Post(reqToken(), reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  452. m.Group("/:index", func() {
  453. m.Combo("").Get(repo.GetPullRequest).
  454. Patch(reqToken(), reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  455. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  456. Post(reqToken(), reqRepoWriter(), bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
  457. })
  458. }, mustAllowPulls, context.ReferencesGitRepo())
  459. m.Group("/statuses", func() {
  460. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  461. Post(reqToken(), reqRepoWriter(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  462. })
  463. m.Group("/commits/:ref", func() {
  464. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  465. m.Get("/statuses", repo.GetCommitStatusesByRef)
  466. })
  467. }, repoAssignment())
  468. })
  469. // Organizations
  470. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  471. m.Get("/users/:username/orgs", org.ListUserOrgs)
  472. m.Group("/orgs/:orgname", func() {
  473. m.Get("/repos", user.ListOrgRepos)
  474. m.Combo("").Get(org.Get).
  475. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit)
  476. m.Group("/members", func() {
  477. m.Get("", org.ListMembers)
  478. m.Combo("/:username").Get(org.IsMember).
  479. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  480. })
  481. m.Group("/public_members", func() {
  482. m.Get("", org.ListPublicMembers)
  483. m.Combo("/:username").Get(org.IsPublicMember).
  484. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  485. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  486. })
  487. m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
  488. Post(bind(api.CreateTeamOption{}), org.CreateTeam)
  489. m.Group("/hooks", func() {
  490. m.Combo("").Get(org.ListHooks).
  491. Post(bind(api.CreateHookOption{}), org.CreateHook)
  492. m.Combo("/:id").Get(org.GetHook).
  493. Patch(reqOrgOwnership(), bind(api.EditHookOption{}), org.EditHook).
  494. Delete(reqOrgOwnership(), org.DeleteHook)
  495. }, reqToken(), reqOrgMembership())
  496. }, orgAssignment(true))
  497. m.Group("/teams/:teamid", func() {
  498. m.Combo("").Get(org.GetTeam).
  499. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  500. Delete(reqOrgOwnership(), org.DeleteTeam)
  501. m.Group("/members", func() {
  502. m.Get("", org.GetTeamMembers)
  503. m.Combo("/:username").
  504. Put(reqOrgOwnership(), org.AddTeamMember).
  505. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  506. })
  507. m.Group("/repos", func() {
  508. m.Get("", org.GetTeamRepos)
  509. m.Combo("/:orgname/:reponame").
  510. Put(org.AddTeamRepository).
  511. Delete(org.RemoveTeamRepository)
  512. })
  513. }, orgAssignment(false, true), reqToken(), reqOrgMembership())
  514. m.Any("/*", func(ctx *context.Context) {
  515. ctx.Error(404)
  516. })
  517. m.Group("/admin", func() {
  518. m.Group("/users", func() {
  519. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  520. m.Group("/:username", func() {
  521. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  522. Delete(admin.DeleteUser)
  523. m.Group("/keys", func() {
  524. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  525. m.Delete("/:id", admin.DeleteUserPublicKey)
  526. })
  527. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  528. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  529. })
  530. })
  531. }, reqAdmin())
  532. m.Group("/topics", func() {
  533. m.Get("/search", repo.TopicSearch)
  534. })
  535. }, context.APIContexter())
  536. }