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