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

552 lines
16 KiB

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