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.

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