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.

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