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

api.go 28 kB

Add basic integration test infrastructure (and new endpoint `/api/v1/version` for testing it) (#741) * Implement '/api/v1/version' * Cleanup and various fixes * Enhance run.sh * Add install_test.go * Add parameter utils.Config for testing handlers * Re-organize TestVersion.go * Rename functions * handling process cleanup properly * Fix missing function renaming * Cleanup the 'retry' logic * Cleanup * Remove unneeded logging code * Logging messages tweaking * Logging message tweaking * Fix logging messages * Use 'const' instead of hardwired numbers * We don't really need retries anymore * Move constant ServerHttpPort to install_test.go * Restore mistakenly removed constant * Add required comments to make the linter happy. * Fix comments and naming to address linter's complaints * Detect Gitea executale version automatically * Remove tests/run.sh, `go test` suffices. * Make `make build` a prerequisite of `make test` * Do not sleep before trying * Speedup the server pinging loop * Use defined const instead of hardwired numbers * Remove redundant error handling * Use a dedicated target for running code.gitea.io/tests * Do not make 'test' depend on 'build' target * Rectify the excluded package list * Remove redundant 'exit 1' * Change the API to allow passing test.T to test handlers * Make testing.T an embedded field * Use assert.Equal to comparing results * Add copyright info * Parametrized logging output * Use tmpdir instead * Eliminate redundant casting * Remove unneeded variable * Fix last commit * Add missing copyright info * Replace fmt.Fprintf with fmt.Fprint * rename the xtest to integration-test * Use Symlink instead of hard-link for cross-device linking * Turn debugging logs on * Follow the existing framework for APIs * Output logs only if test.v is true * Re-order import statements * Enhance the error message * Fix comment which breaks the linter's rule * Rename 'integration-test' to 'e2e-test' for saving keystrokes * Add comment to avoid possible confusion * Rename tests -> integration-tests Also change back the Makefile to use `make integration-test`. * Use tests/integration for now * tests/integration -> integrations Slightly flattened directory hierarchy is better. * Update Makefile accordingly * Fix a missing change in Makefile * govendor update code.gitea.io/sdk/gitea * Fix comment of struct fields * Fix conditional nonsense * Fix missing updates regarding version string changes * Make variable naming more consistent * Check http status code * Rectify error messages
8 years ago
10 years ago
9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
7 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
7 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
7 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
7 years ago
Add API endpoint for accessing repo topics (#7963) * Create API endpoints for repo topics. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Generate swagger Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add documentation to functions Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Grammar fix Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix function comment Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Can't use FindTopics when looking for a single repo topic, as it doesnt use exact match Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add PUT ​/repos​/{owner}​/{repo}​/topics and remove GET ​/repos​/{owner}​/{repo}​/topics * Ignore if topic is sent twice in same request, refactoring. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix topic dropdown with api changes. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Style fix Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Update API documentation Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Better way to handle duplicate topics in slice Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Make response element TopicName an array of strings, instead of using an array of TopicName Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add test cases for API Repo Topics. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix format of tests Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix comments Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix unit tests after adding some more topics to the test fixture. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Update models/topic.go Limit multiple if else if ... Co-Authored-By: Antoine GIRARD <sapk@users.noreply.github.com> * Engine as first parameter in function Co-Authored-By: Antoine GIRARD <sapk@users.noreply.github.com> * Replace magic numbers with http status code constants. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix variable scope Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Test one read with login and one with token Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add some more tests Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Apply suggestions from code review Use empty struct for efficiency Co-Authored-By: Lauris BH <lauris@nix.lv> * Add test case to check access for user with write access Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix access, repo admin required to change topics Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Correct first test to be without token Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Any repo reader should be able to access topics. * No need for string pointer Signed-off-by: David Svantesson <davidsvantesson@gmail.com>
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. // Package v1 Gitea API.
  6. //
  7. // This documentation describes the Gitea API.
  8. //
  9. // Schemes: http, https
  10. // BasePath: /api/v1
  11. // Version: 1.1.1
  12. // License: MIT http://opensource.org/licenses/MIT
  13. //
  14. // Consumes:
  15. // - application/json
  16. // - text/plain
  17. //
  18. // Produces:
  19. // - application/json
  20. // - text/html
  21. //
  22. // Security:
  23. // - BasicAuth :
  24. // - Token :
  25. // - AccessToken :
  26. // - AuthorizationHeaderToken :
  27. // - SudoParam :
  28. // - SudoHeader :
  29. //
  30. // SecurityDefinitions:
  31. // BasicAuth:
  32. // type: basic
  33. // Token:
  34. // type: apiKey
  35. // name: token
  36. // in: query
  37. // AccessToken:
  38. // type: apiKey
  39. // name: access_token
  40. // in: query
  41. // AuthorizationHeaderToken:
  42. // type: apiKey
  43. // name: Authorization
  44. // in: header
  45. // description: API tokens must be prepended with "token" followed by a space.
  46. // SudoParam:
  47. // type: apiKey
  48. // name: sudo
  49. // in: query
  50. // description: Sudo API request as the user provided as the key. Admin privileges are required.
  51. // SudoHeader:
  52. // type: apiKey
  53. // name: Sudo
  54. // in: header
  55. // description: Sudo API request as the user provided as the key. Admin privileges are required.
  56. //
  57. // swagger:meta
  58. package v1
  59. import (
  60. "strings"
  61. "code.gitea.io/gitea/models"
  62. "code.gitea.io/gitea/modules/auth"
  63. "code.gitea.io/gitea/modules/context"
  64. "code.gitea.io/gitea/modules/log"
  65. "code.gitea.io/gitea/modules/setting"
  66. api "code.gitea.io/gitea/modules/structs"
  67. "code.gitea.io/gitea/routers/api/v1/admin"
  68. "code.gitea.io/gitea/routers/api/v1/misc"
  69. "code.gitea.io/gitea/routers/api/v1/org"
  70. "code.gitea.io/gitea/routers/api/v1/repo"
  71. _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
  72. "code.gitea.io/gitea/routers/api/v1/user"
  73. "gitea.com/macaron/binding"
  74. "gitea.com/macaron/macaron"
  75. )
  76. func sudo() macaron.Handler {
  77. return func(ctx *context.APIContext) {
  78. sudo := ctx.Query("sudo")
  79. if len(sudo) == 0 {
  80. sudo = ctx.Req.Header.Get("Sudo")
  81. }
  82. if len(sudo) > 0 {
  83. if ctx.IsSigned && ctx.User.IsAdmin {
  84. user, err := models.GetUserByName(sudo)
  85. if err != nil {
  86. if models.IsErrUserNotExist(err) {
  87. ctx.NotFound()
  88. } else {
  89. ctx.Error(500, "GetUserByName", err)
  90. }
  91. return
  92. }
  93. log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name)
  94. ctx.User = user
  95. } else {
  96. ctx.JSON(403, map[string]string{
  97. "message": "Only administrators allowed to sudo.",
  98. })
  99. return
  100. }
  101. }
  102. }
  103. }
  104. func repoAssignment() macaron.Handler {
  105. return func(ctx *context.APIContext) {
  106. userName := ctx.Params(":username")
  107. repoName := ctx.Params(":reponame")
  108. var (
  109. owner *models.User
  110. err error
  111. )
  112. // Check if the user is the same as the repository owner.
  113. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  114. owner = ctx.User
  115. } else {
  116. owner, err = models.GetUserByName(userName)
  117. if err != nil {
  118. if models.IsErrUserNotExist(err) {
  119. ctx.NotFound()
  120. } else {
  121. ctx.Error(500, "GetUserByName", err)
  122. }
  123. return
  124. }
  125. }
  126. ctx.Repo.Owner = owner
  127. // Get repository.
  128. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  129. if err != nil {
  130. if models.IsErrRepoNotExist(err) {
  131. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  132. if err == nil {
  133. context.RedirectToRepo(ctx.Context, redirectRepoID)
  134. } else if models.IsErrRepoRedirectNotExist(err) {
  135. ctx.NotFound()
  136. } else {
  137. ctx.Error(500, "LookupRepoRedirect", err)
  138. }
  139. } else {
  140. ctx.Error(500, "GetRepositoryByName", err)
  141. }
  142. return
  143. }
  144. repo.Owner = owner
  145. ctx.Repo.Repository = repo
  146. ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
  147. if err != nil {
  148. ctx.Error(500, "GetUserRepoPermission", err)
  149. return
  150. }
  151. if !ctx.Repo.HasAccess() {
  152. ctx.NotFound()
  153. return
  154. }
  155. }
  156. }
  157. // Contexter middleware already checks token for user sign in process.
  158. func reqToken() macaron.Handler {
  159. return func(ctx *context.APIContext) {
  160. if true == ctx.Data["IsApiToken"] {
  161. return
  162. }
  163. if ctx.Context.IsBasicAuth {
  164. ctx.CheckForOTP()
  165. return
  166. }
  167. if ctx.IsSigned {
  168. ctx.RequireCSRF()
  169. return
  170. }
  171. ctx.Context.Error(401)
  172. }
  173. }
  174. func reqBasicAuth() macaron.Handler {
  175. return func(ctx *context.APIContext) {
  176. if !ctx.Context.IsBasicAuth {
  177. ctx.Context.Error(401)
  178. return
  179. }
  180. ctx.CheckForOTP()
  181. }
  182. }
  183. // reqSiteAdmin user should be the site admin
  184. func reqSiteAdmin() macaron.Handler {
  185. return func(ctx *context.Context) {
  186. if !ctx.IsUserSiteAdmin() {
  187. ctx.Error(403)
  188. return
  189. }
  190. }
  191. }
  192. // reqOwner user should be the owner of the repo or site admin.
  193. func reqOwner() macaron.Handler {
  194. return func(ctx *context.Context) {
  195. if !ctx.IsUserRepoOwner() && !ctx.IsUserSiteAdmin() {
  196. ctx.Error(403)
  197. return
  198. }
  199. }
  200. }
  201. // reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin
  202. func reqAdmin() macaron.Handler {
  203. return func(ctx *context.Context) {
  204. if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  205. ctx.Error(403)
  206. return
  207. }
  208. }
  209. }
  210. // reqRepoWriter user should have a permission to write to a repo, or be a site admin
  211. func reqRepoWriter(unitTypes ...models.UnitType) macaron.Handler {
  212. return func(ctx *context.Context) {
  213. if !ctx.IsUserRepoWriter(unitTypes) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  214. ctx.Error(403)
  215. return
  216. }
  217. }
  218. }
  219. // reqRepoReader user should have specific read permission or be a repo admin or a site admin
  220. func reqRepoReader(unitType models.UnitType) macaron.Handler {
  221. return func(ctx *context.Context) {
  222. if !ctx.IsUserRepoReaderSpecific(unitType) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  223. ctx.Error(403)
  224. return
  225. }
  226. }
  227. }
  228. // reqAnyRepoReader user should have any permission to read repository or permissions of site admin
  229. func reqAnyRepoReader() macaron.Handler {
  230. return func(ctx *context.Context) {
  231. if !ctx.IsUserRepoReaderAny() && !ctx.IsUserSiteAdmin() {
  232. ctx.Error(403)
  233. return
  234. }
  235. }
  236. }
  237. // reqOrgOwnership user should be an organization owner, or a site admin
  238. func reqOrgOwnership() macaron.Handler {
  239. return func(ctx *context.APIContext) {
  240. if ctx.Context.IsUserSiteAdmin() {
  241. return
  242. }
  243. var orgID int64
  244. if ctx.Org.Organization != nil {
  245. orgID = ctx.Org.Organization.ID
  246. } else if ctx.Org.Team != nil {
  247. orgID = ctx.Org.Team.OrgID
  248. } else {
  249. ctx.Error(500, "", "reqOrgOwnership: unprepared context")
  250. return
  251. }
  252. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  253. if err != nil {
  254. ctx.Error(500, "IsOrganizationOwner", err)
  255. return
  256. } else if !isOwner {
  257. if ctx.Org.Organization != nil {
  258. ctx.Error(403, "", "Must be an organization owner")
  259. } else {
  260. ctx.NotFound()
  261. }
  262. return
  263. }
  264. }
  265. }
  266. // reqTeamMembership user should be an team member, or a site admin
  267. func reqTeamMembership() macaron.Handler {
  268. return func(ctx *context.APIContext) {
  269. if ctx.Context.IsUserSiteAdmin() {
  270. return
  271. }
  272. if ctx.Org.Team == nil {
  273. ctx.Error(500, "", "reqTeamMembership: unprepared context")
  274. return
  275. }
  276. var orgID = ctx.Org.Team.OrgID
  277. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  278. if err != nil {
  279. ctx.Error(500, "IsOrganizationOwner", err)
  280. return
  281. } else if isOwner {
  282. return
  283. }
  284. if isTeamMember, err := models.IsTeamMember(orgID, ctx.Org.Team.ID, ctx.User.ID); err != nil {
  285. ctx.Error(500, "IsTeamMember", err)
  286. return
  287. } else if !isTeamMember {
  288. isOrgMember, err := models.IsOrganizationMember(orgID, ctx.User.ID)
  289. if err != nil {
  290. ctx.Error(500, "IsOrganizationMember", err)
  291. } else if isOrgMember {
  292. ctx.Error(403, "", "Must be a team member")
  293. } else {
  294. ctx.NotFound()
  295. }
  296. return
  297. }
  298. }
  299. }
  300. // reqOrgMembership user should be an organization member, or a site admin
  301. func reqOrgMembership() macaron.Handler {
  302. return func(ctx *context.APIContext) {
  303. if ctx.Context.IsUserSiteAdmin() {
  304. return
  305. }
  306. var orgID int64
  307. if ctx.Org.Organization != nil {
  308. orgID = ctx.Org.Organization.ID
  309. } else if ctx.Org.Team != nil {
  310. orgID = ctx.Org.Team.OrgID
  311. } else {
  312. ctx.Error(500, "", "reqOrgMembership: unprepared context")
  313. return
  314. }
  315. if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil {
  316. ctx.Error(500, "IsOrganizationMember", err)
  317. return
  318. } else if !isMember {
  319. if ctx.Org.Organization != nil {
  320. ctx.Error(403, "", "Must be an organization member")
  321. } else {
  322. ctx.NotFound()
  323. }
  324. return
  325. }
  326. }
  327. }
  328. func reqGitHook() macaron.Handler {
  329. return func(ctx *context.APIContext) {
  330. if !ctx.User.CanEditGitHook() {
  331. ctx.Error(403, "", "must be allowed to edit Git hooks")
  332. return
  333. }
  334. }
  335. }
  336. func orgAssignment(args ...bool) macaron.Handler {
  337. var (
  338. assignOrg bool
  339. assignTeam bool
  340. )
  341. if len(args) > 0 {
  342. assignOrg = args[0]
  343. }
  344. if len(args) > 1 {
  345. assignTeam = args[1]
  346. }
  347. return func(ctx *context.APIContext) {
  348. ctx.Org = new(context.APIOrganization)
  349. var err error
  350. if assignOrg {
  351. ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname"))
  352. if err != nil {
  353. if models.IsErrOrgNotExist(err) {
  354. ctx.NotFound()
  355. } else {
  356. ctx.Error(500, "GetOrgByName", err)
  357. }
  358. return
  359. }
  360. }
  361. if assignTeam {
  362. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  363. if err != nil {
  364. if models.IsErrUserNotExist(err) {
  365. ctx.NotFound()
  366. } else {
  367. ctx.Error(500, "GetTeamById", err)
  368. }
  369. return
  370. }
  371. }
  372. }
  373. }
  374. func mustEnableIssues(ctx *context.APIContext) {
  375. if !ctx.Repo.CanRead(models.UnitTypeIssues) {
  376. if log.IsTrace() {
  377. if ctx.IsSigned {
  378. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  379. "User in Repo has Permissions: %-+v",
  380. ctx.User,
  381. models.UnitTypeIssues,
  382. ctx.Repo.Repository,
  383. ctx.Repo.Permission)
  384. } else {
  385. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  386. "Anonymous user in Repo has Permissions: %-+v",
  387. models.UnitTypeIssues,
  388. ctx.Repo.Repository,
  389. ctx.Repo.Permission)
  390. }
  391. }
  392. ctx.NotFound()
  393. return
  394. }
  395. }
  396. func mustAllowPulls(ctx *context.APIContext) {
  397. if !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) {
  398. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  399. if ctx.IsSigned {
  400. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  401. "User in Repo has Permissions: %-+v",
  402. ctx.User,
  403. models.UnitTypePullRequests,
  404. ctx.Repo.Repository,
  405. ctx.Repo.Permission)
  406. } else {
  407. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  408. "Anonymous user in Repo has Permissions: %-+v",
  409. models.UnitTypePullRequests,
  410. ctx.Repo.Repository,
  411. ctx.Repo.Permission)
  412. }
  413. }
  414. ctx.NotFound()
  415. return
  416. }
  417. }
  418. func mustEnableIssuesOrPulls(ctx *context.APIContext) {
  419. if !ctx.Repo.CanRead(models.UnitTypeIssues) &&
  420. !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) {
  421. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  422. if ctx.IsSigned {
  423. log.Trace("Permission Denied: User %-v cannot read %-v and %-v in Repo %-v\n"+
  424. "User in Repo has Permissions: %-+v",
  425. ctx.User,
  426. models.UnitTypeIssues,
  427. models.UnitTypePullRequests,
  428. ctx.Repo.Repository,
  429. ctx.Repo.Permission)
  430. } else {
  431. log.Trace("Permission Denied: Anonymous user cannot read %-v and %-v in Repo %-v\n"+
  432. "Anonymous user in Repo has Permissions: %-+v",
  433. models.UnitTypeIssues,
  434. models.UnitTypePullRequests,
  435. ctx.Repo.Repository,
  436. ctx.Repo.Permission)
  437. }
  438. }
  439. ctx.NotFound()
  440. return
  441. }
  442. }
  443. func mustEnableUserHeatmap(ctx *context.APIContext) {
  444. if !setting.Service.EnableUserHeatmap {
  445. ctx.NotFound()
  446. return
  447. }
  448. }
  449. func mustNotBeArchived(ctx *context.APIContext) {
  450. if ctx.Repo.Repository.IsArchived {
  451. ctx.NotFound()
  452. return
  453. }
  454. }
  455. // RegisterRoutes registers all v1 APIs routes to web application.
  456. // FIXME: custom form error response
  457. func RegisterRoutes(m *macaron.Macaron) {
  458. bind := binding.Bind
  459. if setting.API.EnableSwagger {
  460. m.Get("/swagger", misc.Swagger) //Render V1 by default
  461. }
  462. m.Group("/v1", func() {
  463. // Miscellaneous
  464. if setting.API.EnableSwagger {
  465. m.Get("/swagger", misc.Swagger)
  466. }
  467. m.Get("/version", misc.Version)
  468. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  469. m.Post("/markdown/raw", misc.MarkdownRaw)
  470. // Users
  471. m.Group("/users", func() {
  472. m.Get("/search", user.Search)
  473. m.Group("/:username", func() {
  474. m.Get("", user.GetInfo)
  475. m.Get("/heatmap", mustEnableUserHeatmap, user.GetUserHeatmapData)
  476. m.Get("/repos", user.ListUserRepos)
  477. m.Group("/tokens", func() {
  478. m.Combo("").Get(user.ListAccessTokens).
  479. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  480. m.Combo("/:id").Delete(user.DeleteAccessToken)
  481. }, reqBasicAuth())
  482. })
  483. })
  484. m.Group("/users", func() {
  485. m.Group("/:username", func() {
  486. m.Get("/keys", user.ListPublicKeys)
  487. m.Get("/gpg_keys", user.ListGPGKeys)
  488. m.Get("/followers", user.ListFollowers)
  489. m.Group("/following", func() {
  490. m.Get("", user.ListFollowing)
  491. m.Get("/:target", user.CheckFollowing)
  492. })
  493. m.Get("/starred", user.GetStarredRepos)
  494. m.Get("/subscriptions", user.GetWatchedRepos)
  495. })
  496. }, reqToken())
  497. m.Group("/user", func() {
  498. m.Get("", user.GetAuthenticatedUser)
  499. m.Combo("/emails").Get(user.ListEmails).
  500. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  501. Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)
  502. m.Get("/followers", user.ListMyFollowers)
  503. m.Group("/following", func() {
  504. m.Get("", user.ListMyFollowing)
  505. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  506. })
  507. m.Group("/keys", func() {
  508. m.Combo("").Get(user.ListMyPublicKeys).
  509. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  510. m.Combo("/:id").Get(user.GetPublicKey).
  511. Delete(user.DeletePublicKey)
  512. })
  513. m.Group("/gpg_keys", func() {
  514. m.Combo("").Get(user.ListMyGPGKeys).
  515. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  516. m.Combo("/:id").Get(user.GetGPGKey).
  517. Delete(user.DeleteGPGKey)
  518. })
  519. m.Combo("/repos").Get(user.ListMyRepos).
  520. Post(bind(api.CreateRepoOption{}), repo.Create)
  521. m.Group("/starred", func() {
  522. m.Get("", user.GetMyStarredRepos)
  523. m.Group("/:username/:reponame", func() {
  524. m.Get("", user.IsStarring)
  525. m.Put("", user.Star)
  526. m.Delete("", user.Unstar)
  527. }, repoAssignment())
  528. })
  529. m.Get("/times", repo.ListMyTrackedTimes)
  530. m.Get("/subscriptions", user.GetMyWatchedRepos)
  531. m.Get("/teams", org.ListUserTeams)
  532. }, reqToken())
  533. // Repositories
  534. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  535. m.Group("/repos", func() {
  536. m.Get("/search", repo.Search)
  537. })
  538. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  539. m.Group("/repos", func() {
  540. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  541. m.Group("/:username/:reponame", func() {
  542. m.Combo("").Get(reqAnyRepoReader(), repo.Get).
  543. Delete(reqToken(), reqOwner(), repo.Delete).
  544. Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit)
  545. m.Group("/hooks", func() {
  546. m.Combo("").Get(repo.ListHooks).
  547. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  548. m.Group("/:id", func() {
  549. m.Combo("").Get(repo.GetHook).
  550. Patch(bind(api.EditHookOption{}), repo.EditHook).
  551. Delete(repo.DeleteHook)
  552. m.Post("/tests", context.RepoRef(), repo.TestHook)
  553. })
  554. m.Group("/git", func() {
  555. m.Combo("").Get(repo.ListGitHooks)
  556. m.Group("/:id", func() {
  557. m.Combo("").Get(repo.GetGitHook).
  558. Patch(bind(api.EditGitHookOption{}), repo.EditGitHook).
  559. Delete(repo.DeleteGitHook)
  560. })
  561. }, reqGitHook(), context.ReferencesGitRepo(true))
  562. }, reqToken(), reqAdmin())
  563. m.Group("/collaborators", func() {
  564. m.Get("", repo.ListCollaborators)
  565. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  566. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  567. Delete(repo.DeleteCollaborator)
  568. }, reqToken(), reqAdmin())
  569. m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), reqRepoReader(models.UnitTypeCode), repo.GetRawFile)
  570. m.Get("/archive/*", reqRepoReader(models.UnitTypeCode), repo.GetArchive)
  571. m.Combo("/forks").Get(repo.ListForks).
  572. Post(reqToken(), reqRepoReader(models.UnitTypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
  573. m.Group("/branches", func() {
  574. m.Get("", repo.ListBranches)
  575. m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
  576. }, reqRepoReader(models.UnitTypeCode))
  577. m.Group("/tags", func() {
  578. m.Get("", repo.ListTags)
  579. }, reqRepoReader(models.UnitTypeCode))
  580. m.Group("/keys", func() {
  581. m.Combo("").Get(repo.ListDeployKeys).
  582. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  583. m.Combo("/:id").Get(repo.GetDeployKey).
  584. Delete(repo.DeleteDeploykey)
  585. }, reqToken(), reqAdmin())
  586. m.Group("/times", func() {
  587. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  588. m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)
  589. }, mustEnableIssues)
  590. m.Group("/issues", func() {
  591. m.Combo("").Get(repo.ListIssues).
  592. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue)
  593. m.Group("/comments", func() {
  594. m.Get("", repo.ListRepoIssueComments)
  595. m.Combo("/:id", reqToken()).
  596. Patch(mustNotBeArchived, bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  597. Delete(repo.DeleteIssueComment)
  598. })
  599. m.Group("/:index", func() {
  600. m.Combo("").Get(repo.GetIssue).
  601. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  602. m.Group("/comments", func() {
  603. m.Combo("").Get(repo.ListIssueComments).
  604. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  605. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  606. Delete(repo.DeleteIssueCommentDeprecated)
  607. })
  608. m.Group("/labels", func() {
  609. m.Combo("").Get(repo.ListIssueLabels).
  610. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  611. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  612. Delete(reqToken(), repo.ClearIssueLabels)
  613. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  614. })
  615. m.Group("/times", func() {
  616. m.Combo("").Get(repo.ListTrackedTimes).
  617. Post(reqToken(), bind(api.AddTimeOption{}), repo.AddTime)
  618. })
  619. m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  620. m.Group("/stopwatch", func() {
  621. m.Post("/start", reqToken(), repo.StartIssueStopwatch)
  622. m.Post("/stop", reqToken(), repo.StopIssueStopwatch)
  623. })
  624. })
  625. }, mustEnableIssuesOrPulls)
  626. m.Group("/labels", func() {
  627. m.Combo("").Get(repo.ListLabels).
  628. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel)
  629. m.Combo("/:id").Get(repo.GetLabel).
  630. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel).
  631. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteLabel)
  632. })
  633. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  634. m.Post("/markdown/raw", misc.MarkdownRaw)
  635. m.Group("/milestones", func() {
  636. m.Combo("").Get(repo.ListMilestones).
  637. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  638. m.Combo("/:id").Get(repo.GetMilestone).
  639. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  640. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteMilestone)
  641. })
  642. m.Get("/stargazers", repo.ListStargazers)
  643. m.Get("/subscribers", repo.ListSubscribers)
  644. m.Group("/subscription", func() {
  645. m.Get("", user.IsWatching)
  646. m.Put("", reqToken(), user.Watch)
  647. m.Delete("", reqToken(), user.Unwatch)
  648. })
  649. m.Group("/releases", func() {
  650. m.Combo("").Get(repo.ListReleases).
  651. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  652. m.Group("/:id", func() {
  653. m.Combo("").Get(repo.GetRelease).
  654. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.EditReleaseOption{}), repo.EditRelease).
  655. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteRelease)
  656. m.Group("/assets", func() {
  657. m.Combo("").Get(repo.ListReleaseAttachments).
  658. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.CreateReleaseAttachment)
  659. m.Combo("/:asset").Get(repo.GetReleaseAttachment).
  660. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  661. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteReleaseAttachment)
  662. })
  663. })
  664. }, reqRepoReader(models.UnitTypeReleases))
  665. m.Post("/mirror-sync", reqToken(), reqRepoWriter(models.UnitTypeCode), repo.MirrorSync)
  666. m.Get("/editorconfig/:filename", context.RepoRef(), reqRepoReader(models.UnitTypeCode), repo.GetEditorconfig)
  667. m.Group("/pulls", func() {
  668. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  669. Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  670. m.Group("/:index", func() {
  671. m.Combo("").Get(repo.GetPullRequest).
  672. Patch(reqToken(), reqRepoWriter(models.UnitTypePullRequests), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  673. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  674. Post(reqToken(), mustNotBeArchived, reqRepoWriter(models.UnitTypePullRequests), bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
  675. })
  676. }, mustAllowPulls, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(false))
  677. m.Group("/statuses", func() {
  678. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  679. Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  680. }, reqRepoReader(models.UnitTypeCode))
  681. m.Group("/commits", func() {
  682. m.Get("", repo.GetAllCommits)
  683. m.Group("/:ref", func() {
  684. // TODO: Add m.Get("") for single commit (https://developer.github.com/v3/repos/commits/#get-a-single-commit)
  685. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  686. m.Get("/statuses", repo.GetCommitStatusesByRef)
  687. })
  688. }, reqRepoReader(models.UnitTypeCode))
  689. m.Group("/git", func() {
  690. m.Group("/commits", func() {
  691. m.Get("/:sha", repo.GetSingleCommit)
  692. })
  693. m.Get("/refs", repo.GetGitAllRefs)
  694. m.Get("/refs/*", repo.GetGitRefs)
  695. m.Get("/trees/:sha", context.RepoRef(), repo.GetTree)
  696. m.Get("/blobs/:sha", context.RepoRef(), repo.GetBlob)
  697. m.Get("/tags/:sha", context.RepoRef(), repo.GetTag)
  698. }, reqRepoReader(models.UnitTypeCode))
  699. m.Group("/contents", func() {
  700. m.Get("", repo.GetContentsList)
  701. m.Get("/*", repo.GetContents)
  702. m.Group("/*", func() {
  703. m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile)
  704. m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile)
  705. m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile)
  706. }, reqRepoWriter(models.UnitTypeCode), reqToken())
  707. }, reqRepoReader(models.UnitTypeCode))
  708. m.Group("/topics", func() {
  709. m.Combo("").Get(repo.ListTopics).
  710. Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics)
  711. m.Group("/:topic", func() {
  712. m.Combo("").Put(reqToken(), repo.AddTopic).
  713. Delete(reqToken(), repo.DeleteTopic)
  714. }, reqAdmin())
  715. }, reqAnyRepoReader())
  716. }, repoAssignment())
  717. })
  718. // Organizations
  719. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  720. m.Get("/users/:username/orgs", org.ListUserOrgs)
  721. m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
  722. m.Group("/orgs/:orgname", func() {
  723. m.Get("/repos", user.ListOrgRepos)
  724. m.Combo("").Get(org.Get).
  725. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit).
  726. Delete(reqToken(), reqOrgOwnership(), org.Delete)
  727. m.Group("/members", func() {
  728. m.Get("", org.ListMembers)
  729. m.Combo("/:username").Get(org.IsMember).
  730. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  731. })
  732. m.Group("/public_members", func() {
  733. m.Get("", org.ListPublicMembers)
  734. m.Combo("/:username").Get(org.IsPublicMember).
  735. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  736. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  737. })
  738. m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
  739. Post(reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam)
  740. m.Group("/hooks", func() {
  741. m.Combo("").Get(org.ListHooks).
  742. Post(bind(api.CreateHookOption{}), org.CreateHook)
  743. m.Combo("/:id").Get(org.GetHook).
  744. Patch(bind(api.EditHookOption{}), org.EditHook).
  745. Delete(org.DeleteHook)
  746. }, reqToken(), reqOrgOwnership())
  747. }, orgAssignment(true))
  748. m.Group("/teams/:teamid", func() {
  749. m.Combo("").Get(org.GetTeam).
  750. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  751. Delete(reqOrgOwnership(), org.DeleteTeam)
  752. m.Group("/members", func() {
  753. m.Get("", org.GetTeamMembers)
  754. m.Combo("/:username").
  755. Get(org.GetTeamMember).
  756. Put(reqOrgOwnership(), org.AddTeamMember).
  757. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  758. })
  759. m.Group("/repos", func() {
  760. m.Get("", org.GetTeamRepos)
  761. m.Combo("/:orgname/:reponame").
  762. Put(org.AddTeamRepository).
  763. Delete(org.RemoveTeamRepository)
  764. })
  765. }, orgAssignment(false, true), reqToken(), reqTeamMembership())
  766. m.Any("/*", func(ctx *context.APIContext) {
  767. ctx.NotFound()
  768. })
  769. m.Group("/admin", func() {
  770. m.Get("/orgs", admin.GetAllOrgs)
  771. m.Group("/users", func() {
  772. m.Get("", admin.GetAllUsers)
  773. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  774. m.Group("/:username", func() {
  775. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  776. Delete(admin.DeleteUser)
  777. m.Group("/keys", func() {
  778. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  779. m.Delete("/:id", admin.DeleteUserPublicKey)
  780. })
  781. m.Get("/orgs", org.ListUserOrgs)
  782. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  783. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  784. })
  785. })
  786. }, reqToken(), reqSiteAdmin())
  787. m.Group("/topics", func() {
  788. m.Get("/search", repo.TopicSearch)
  789. })
  790. }, securityHeaders(), context.APIContexter(), sudo())
  791. }
  792. func securityHeaders() macaron.Handler {
  793. return func(ctx *macaron.Context) {
  794. ctx.Resp.Before(func(w macaron.ResponseWriter) {
  795. // CORB: https://www.chromium.org/Home/chromium-security/corb-for-developers
  796. // http://stackoverflow.com/a/3146618/244009
  797. w.Header().Set("x-content-type-options", "nosniff")
  798. })
  799. }
  800. }