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