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.

api.go 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. "net/http"
  61. "strings"
  62. "code.gitea.io/gitea/models"
  63. "code.gitea.io/gitea/modules/auth"
  64. "code.gitea.io/gitea/modules/context"
  65. "code.gitea.io/gitea/modules/log"
  66. "code.gitea.io/gitea/modules/setting"
  67. api "code.gitea.io/gitea/modules/structs"
  68. "code.gitea.io/gitea/routers/api/v1/admin"
  69. "code.gitea.io/gitea/routers/api/v1/misc"
  70. "code.gitea.io/gitea/routers/api/v1/notify"
  71. "code.gitea.io/gitea/routers/api/v1/org"
  72. "code.gitea.io/gitea/routers/api/v1/repo"
  73. "code.gitea.io/gitea/routers/api/v1/settings"
  74. _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
  75. "code.gitea.io/gitea/routers/api/v1/user"
  76. "gitea.com/macaron/binding"
  77. "gitea.com/macaron/macaron"
  78. )
  79. func sudo() macaron.Handler {
  80. return func(ctx *context.APIContext) {
  81. sudo := ctx.Query("sudo")
  82. if len(sudo) == 0 {
  83. sudo = ctx.Req.Header.Get("Sudo")
  84. }
  85. if len(sudo) > 0 {
  86. if ctx.IsSigned && ctx.User.IsAdmin {
  87. user, err := models.GetUserByName(sudo)
  88. if err != nil {
  89. if models.IsErrUserNotExist(err) {
  90. ctx.NotFound()
  91. } else {
  92. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  93. }
  94. return
  95. }
  96. log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name)
  97. ctx.User = user
  98. } else {
  99. ctx.JSON(http.StatusForbidden, map[string]string{
  100. "message": "Only administrators allowed to sudo.",
  101. })
  102. return
  103. }
  104. }
  105. }
  106. }
  107. func repoAssignment() macaron.Handler {
  108. return func(ctx *context.APIContext) {
  109. userName := ctx.Params(":username")
  110. repoName := ctx.Params(":reponame")
  111. var (
  112. owner *models.User
  113. err error
  114. )
  115. // Check if the user is the same as the repository owner.
  116. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  117. owner = ctx.User
  118. } else {
  119. owner, err = models.GetUserByName(userName)
  120. if err != nil {
  121. if models.IsErrUserNotExist(err) {
  122. ctx.NotFound()
  123. } else {
  124. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  125. }
  126. return
  127. }
  128. }
  129. ctx.Repo.Owner = owner
  130. // Get repository.
  131. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  132. if err != nil {
  133. if models.IsErrRepoNotExist(err) {
  134. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  135. if err == nil {
  136. context.RedirectToRepo(ctx.Context, redirectRepoID)
  137. } else if models.IsErrRepoRedirectNotExist(err) {
  138. ctx.NotFound()
  139. } else {
  140. ctx.Error(http.StatusInternalServerError, "LookupRepoRedirect", err)
  141. }
  142. } else {
  143. ctx.Error(http.StatusInternalServerError, "GetRepositoryByName", err)
  144. }
  145. return
  146. }
  147. repo.Owner = owner
  148. ctx.Repo.Repository = repo
  149. ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
  150. if err != nil {
  151. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  152. return
  153. }
  154. if !ctx.Repo.HasAccess() {
  155. ctx.NotFound()
  156. return
  157. }
  158. }
  159. }
  160. // Contexter middleware already checks token for user sign in process.
  161. func reqToken() macaron.Handler {
  162. return func(ctx *context.APIContext) {
  163. if true == ctx.Data["IsApiToken"] {
  164. return
  165. }
  166. if ctx.Context.IsBasicAuth {
  167. ctx.CheckForOTP()
  168. return
  169. }
  170. if ctx.IsSigned {
  171. ctx.RequireCSRF()
  172. return
  173. }
  174. ctx.Context.Error(http.StatusUnauthorized)
  175. }
  176. }
  177. func reqBasicAuth() macaron.Handler {
  178. return func(ctx *context.APIContext) {
  179. if !ctx.Context.IsBasicAuth {
  180. ctx.Context.Error(http.StatusUnauthorized)
  181. return
  182. }
  183. ctx.CheckForOTP()
  184. }
  185. }
  186. // reqSiteAdmin user should be the site admin
  187. func reqSiteAdmin() macaron.Handler {
  188. return func(ctx *context.Context) {
  189. if !ctx.IsUserSiteAdmin() {
  190. ctx.Error(http.StatusForbidden)
  191. return
  192. }
  193. }
  194. }
  195. // reqOwner user should be the owner of the repo or site admin.
  196. func reqOwner() macaron.Handler {
  197. return func(ctx *context.Context) {
  198. if !ctx.IsUserRepoOwner() && !ctx.IsUserSiteAdmin() {
  199. ctx.Error(http.StatusForbidden)
  200. return
  201. }
  202. }
  203. }
  204. // reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin
  205. func reqAdmin() macaron.Handler {
  206. return func(ctx *context.Context) {
  207. if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  208. ctx.Error(http.StatusForbidden)
  209. return
  210. }
  211. }
  212. }
  213. // reqRepoWriter user should have a permission to write to a repo, or be a site admin
  214. func reqRepoWriter(unitTypes ...models.UnitType) macaron.Handler {
  215. return func(ctx *context.Context) {
  216. if !ctx.IsUserRepoWriter(unitTypes) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  217. ctx.Error(http.StatusForbidden)
  218. return
  219. }
  220. }
  221. }
  222. // reqRepoReader user should have specific read permission or be a repo admin or a site admin
  223. func reqRepoReader(unitType models.UnitType) macaron.Handler {
  224. return func(ctx *context.Context) {
  225. if !ctx.IsUserRepoReaderSpecific(unitType) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  226. ctx.Error(http.StatusForbidden)
  227. return
  228. }
  229. }
  230. }
  231. // reqAnyRepoReader user should have any permission to read repository or permissions of site admin
  232. func reqAnyRepoReader() macaron.Handler {
  233. return func(ctx *context.Context) {
  234. if !ctx.IsUserRepoReaderAny() && !ctx.IsUserSiteAdmin() {
  235. ctx.Error(http.StatusForbidden)
  236. return
  237. }
  238. }
  239. }
  240. // reqOrgOwnership user should be an organization owner, or a site admin
  241. func reqOrgOwnership() macaron.Handler {
  242. return func(ctx *context.APIContext) {
  243. if ctx.Context.IsUserSiteAdmin() {
  244. return
  245. }
  246. var orgID int64
  247. if ctx.Org.Organization != nil {
  248. orgID = ctx.Org.Organization.ID
  249. } else if ctx.Org.Team != nil {
  250. orgID = ctx.Org.Team.OrgID
  251. } else {
  252. ctx.Error(http.StatusInternalServerError, "", "reqOrgOwnership: unprepared context")
  253. return
  254. }
  255. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  256. if err != nil {
  257. ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
  258. return
  259. } else if !isOwner {
  260. if ctx.Org.Organization != nil {
  261. ctx.Error(http.StatusForbidden, "", "Must be an organization owner")
  262. } else {
  263. ctx.NotFound()
  264. }
  265. return
  266. }
  267. }
  268. }
  269. // reqTeamMembership user should be an team member, or a site admin
  270. func reqTeamMembership() macaron.Handler {
  271. return func(ctx *context.APIContext) {
  272. if ctx.Context.IsUserSiteAdmin() {
  273. return
  274. }
  275. if ctx.Org.Team == nil {
  276. ctx.Error(http.StatusInternalServerError, "", "reqTeamMembership: unprepared context")
  277. return
  278. }
  279. var orgID = ctx.Org.Team.OrgID
  280. isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
  281. if err != nil {
  282. ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
  283. return
  284. } else if isOwner {
  285. return
  286. }
  287. if isTeamMember, err := models.IsTeamMember(orgID, ctx.Org.Team.ID, ctx.User.ID); err != nil {
  288. ctx.Error(http.StatusInternalServerError, "IsTeamMember", err)
  289. return
  290. } else if !isTeamMember {
  291. isOrgMember, err := models.IsOrganizationMember(orgID, ctx.User.ID)
  292. if err != nil {
  293. ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
  294. } else if isOrgMember {
  295. ctx.Error(http.StatusForbidden, "", "Must be a team member")
  296. } else {
  297. ctx.NotFound()
  298. }
  299. return
  300. }
  301. }
  302. }
  303. // reqOrgMembership user should be an organization member, or a site admin
  304. func reqOrgMembership() macaron.Handler {
  305. return func(ctx *context.APIContext) {
  306. if ctx.Context.IsUserSiteAdmin() {
  307. return
  308. }
  309. var orgID int64
  310. if ctx.Org.Organization != nil {
  311. orgID = ctx.Org.Organization.ID
  312. } else if ctx.Org.Team != nil {
  313. orgID = ctx.Org.Team.OrgID
  314. } else {
  315. ctx.Error(http.StatusInternalServerError, "", "reqOrgMembership: unprepared context")
  316. return
  317. }
  318. if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil {
  319. ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
  320. return
  321. } else if !isMember {
  322. if ctx.Org.Organization != nil {
  323. ctx.Error(http.StatusForbidden, "", "Must be an organization member")
  324. } else {
  325. ctx.NotFound()
  326. }
  327. return
  328. }
  329. }
  330. }
  331. func reqGitHook() macaron.Handler {
  332. return func(ctx *context.APIContext) {
  333. if !ctx.User.CanEditGitHook() {
  334. ctx.Error(http.StatusForbidden, "", "must be allowed to edit Git hooks")
  335. return
  336. }
  337. }
  338. }
  339. func orgAssignment(args ...bool) macaron.Handler {
  340. var (
  341. assignOrg bool
  342. assignTeam bool
  343. )
  344. if len(args) > 0 {
  345. assignOrg = args[0]
  346. }
  347. if len(args) > 1 {
  348. assignTeam = args[1]
  349. }
  350. return func(ctx *context.APIContext) {
  351. ctx.Org = new(context.APIOrganization)
  352. var err error
  353. if assignOrg {
  354. ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":org"))
  355. if err != nil {
  356. if models.IsErrOrgNotExist(err) {
  357. ctx.NotFound()
  358. } else {
  359. ctx.Error(http.StatusInternalServerError, "GetOrgByName", err)
  360. }
  361. return
  362. }
  363. }
  364. if assignTeam {
  365. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  366. if err != nil {
  367. if models.IsErrUserNotExist(err) {
  368. ctx.NotFound()
  369. } else {
  370. ctx.Error(http.StatusInternalServerError, "GetTeamById", err)
  371. }
  372. return
  373. }
  374. }
  375. }
  376. }
  377. func mustEnableIssues(ctx *context.APIContext) {
  378. if !ctx.Repo.CanRead(models.UnitTypeIssues) {
  379. if log.IsTrace() {
  380. if ctx.IsSigned {
  381. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  382. "User in Repo has Permissions: %-+v",
  383. ctx.User,
  384. models.UnitTypeIssues,
  385. ctx.Repo.Repository,
  386. ctx.Repo.Permission)
  387. } else {
  388. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  389. "Anonymous user in Repo has Permissions: %-+v",
  390. models.UnitTypeIssues,
  391. ctx.Repo.Repository,
  392. ctx.Repo.Permission)
  393. }
  394. }
  395. ctx.NotFound()
  396. return
  397. }
  398. }
  399. func mustAllowPulls(ctx *context.APIContext) {
  400. if !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) {
  401. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  402. if ctx.IsSigned {
  403. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  404. "User in Repo has Permissions: %-+v",
  405. ctx.User,
  406. models.UnitTypePullRequests,
  407. ctx.Repo.Repository,
  408. ctx.Repo.Permission)
  409. } else {
  410. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  411. "Anonymous user in Repo has Permissions: %-+v",
  412. models.UnitTypePullRequests,
  413. ctx.Repo.Repository,
  414. ctx.Repo.Permission)
  415. }
  416. }
  417. ctx.NotFound()
  418. return
  419. }
  420. }
  421. func mustEnableIssuesOrPulls(ctx *context.APIContext) {
  422. if !ctx.Repo.CanRead(models.UnitTypeIssues) &&
  423. !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) {
  424. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  425. if ctx.IsSigned {
  426. log.Trace("Permission Denied: User %-v cannot read %-v and %-v in Repo %-v\n"+
  427. "User in Repo has Permissions: %-+v",
  428. ctx.User,
  429. models.UnitTypeIssues,
  430. models.UnitTypePullRequests,
  431. ctx.Repo.Repository,
  432. ctx.Repo.Permission)
  433. } else {
  434. log.Trace("Permission Denied: Anonymous user cannot read %-v and %-v in Repo %-v\n"+
  435. "Anonymous user in Repo has Permissions: %-+v",
  436. models.UnitTypeIssues,
  437. models.UnitTypePullRequests,
  438. ctx.Repo.Repository,
  439. ctx.Repo.Permission)
  440. }
  441. }
  442. ctx.NotFound()
  443. return
  444. }
  445. }
  446. func mustEnableUserHeatmap(ctx *context.APIContext) {
  447. if !setting.Service.EnableUserHeatmap {
  448. ctx.NotFound()
  449. return
  450. }
  451. }
  452. func mustNotBeArchived(ctx *context.APIContext) {
  453. if ctx.Repo.Repository.IsArchived {
  454. ctx.NotFound()
  455. return
  456. }
  457. }
  458. // RegisterRoutes registers all v1 APIs routes to web application.
  459. // FIXME: custom form error response
  460. func RegisterRoutes(m *macaron.Macaron) {
  461. bind := binding.Bind
  462. if setting.API.EnableSwagger {
  463. m.Get("/swagger", misc.Swagger) // Render V1 by default
  464. }
  465. m.Group("/v1", func() {
  466. // Miscellaneous
  467. if setting.API.EnableSwagger {
  468. m.Get("/swagger", misc.Swagger)
  469. }
  470. m.Get("/version", misc.Version)
  471. m.Get("/signing-key.gpg", misc.SigningKey)
  472. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  473. m.Post("/markdown/raw", misc.MarkdownRaw)
  474. m.Group("/settings", func() {
  475. m.Get("/ui", settings.GetGeneralUISettings)
  476. m.Get("/repository", settings.GetGeneralRepoSettings)
  477. })
  478. // Notifications
  479. m.Group("/notifications", func() {
  480. m.Combo("").
  481. Get(notify.ListNotifications).
  482. Put(notify.ReadNotifications)
  483. m.Get("/new", notify.NewAvailable)
  484. m.Combo("/threads/:id").
  485. Get(notify.GetThread).
  486. Patch(notify.ReadThread)
  487. }, reqToken())
  488. // Users
  489. m.Group("/users", func() {
  490. m.Get("/search", user.Search)
  491. m.Group("/:username", func() {
  492. m.Get("", user.GetInfo)
  493. m.Get("/heatmap", mustEnableUserHeatmap, user.GetUserHeatmapData)
  494. m.Get("/repos", user.ListUserRepos)
  495. m.Group("/tokens", func() {
  496. m.Combo("").Get(user.ListAccessTokens).
  497. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  498. m.Combo("/:id").Delete(user.DeleteAccessToken)
  499. }, reqBasicAuth())
  500. })
  501. })
  502. m.Group("/users", func() {
  503. m.Group("/:username", func() {
  504. m.Get("/keys", user.ListPublicKeys)
  505. m.Get("/gpg_keys", user.ListGPGKeys)
  506. m.Get("/followers", user.ListFollowers)
  507. m.Group("/following", func() {
  508. m.Get("", user.ListFollowing)
  509. m.Get("/:target", user.CheckFollowing)
  510. })
  511. m.Get("/starred", user.GetStarredRepos)
  512. m.Get("/subscriptions", user.GetWatchedRepos)
  513. })
  514. }, reqToken())
  515. m.Group("/user", func() {
  516. m.Get("", user.GetAuthenticatedUser)
  517. m.Combo("/emails").Get(user.ListEmails).
  518. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  519. Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)
  520. m.Get("/followers", user.ListMyFollowers)
  521. m.Group("/following", func() {
  522. m.Get("", user.ListMyFollowing)
  523. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  524. })
  525. m.Group("/keys", func() {
  526. m.Combo("").Get(user.ListMyPublicKeys).
  527. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  528. m.Combo("/:id").Get(user.GetPublicKey).
  529. Delete(user.DeletePublicKey)
  530. })
  531. m.Group("/applications", func() {
  532. m.Combo("/oauth2").
  533. Get(user.ListOauth2Applications).
  534. Post(bind(api.CreateOAuth2ApplicationOptions{}), user.CreateOauth2Application)
  535. m.Combo("/oauth2/:id").
  536. Delete(user.DeleteOauth2Application).
  537. Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application).
  538. Get(user.GetOauth2Application)
  539. }, reqToken())
  540. m.Group("/gpg_keys", func() {
  541. m.Combo("").Get(user.ListMyGPGKeys).
  542. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  543. m.Combo("/:id").Get(user.GetGPGKey).
  544. Delete(user.DeleteGPGKey)
  545. })
  546. m.Combo("/repos").Get(user.ListMyRepos).
  547. Post(bind(api.CreateRepoOption{}), repo.Create)
  548. m.Group("/starred", func() {
  549. m.Get("", user.GetMyStarredRepos)
  550. m.Group("/:username/:reponame", func() {
  551. m.Get("", user.IsStarring)
  552. m.Put("", user.Star)
  553. m.Delete("", user.Unstar)
  554. }, repoAssignment())
  555. })
  556. m.Get("/times", repo.ListMyTrackedTimes)
  557. m.Get("/stopwatches", repo.GetStopwatches)
  558. m.Get("/subscriptions", user.GetMyWatchedRepos)
  559. m.Get("/teams", org.ListUserTeams)
  560. }, reqToken())
  561. // Repositories
  562. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated)
  563. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  564. m.Group("/repos", func() {
  565. m.Get("/search", repo.Search)
  566. m.Get("/issues/search", repo.SearchIssues)
  567. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  568. m.Group("/:username/:reponame", func() {
  569. m.Combo("").Get(reqAnyRepoReader(), repo.Get).
  570. Delete(reqToken(), reqOwner(), repo.Delete).
  571. Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), context.RepoRef(), repo.Edit)
  572. m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer)
  573. m.Combo("/notifications").
  574. Get(reqToken(), notify.ListRepoNotifications).
  575. Put(reqToken(), notify.ReadRepoNotifications)
  576. m.Group("/hooks", func() {
  577. m.Combo("").Get(repo.ListHooks).
  578. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  579. m.Group("/:id", func() {
  580. m.Combo("").Get(repo.GetHook).
  581. Patch(bind(api.EditHookOption{}), repo.EditHook).
  582. Delete(repo.DeleteHook)
  583. m.Post("/tests", context.RepoRef(), repo.TestHook)
  584. })
  585. m.Group("/git", func() {
  586. m.Combo("").Get(repo.ListGitHooks)
  587. m.Group("/:id", func() {
  588. m.Combo("").Get(repo.GetGitHook).
  589. Patch(bind(api.EditGitHookOption{}), repo.EditGitHook).
  590. Delete(repo.DeleteGitHook)
  591. })
  592. }, reqGitHook(), context.ReferencesGitRepo(true))
  593. }, reqToken(), reqAdmin())
  594. m.Group("/collaborators", func() {
  595. m.Get("", reqAnyRepoReader(), repo.ListCollaborators)
  596. m.Combo("/:collaborator").Get(reqAnyRepoReader(), repo.IsCollaborator).
  597. Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  598. Delete(reqAdmin(), repo.DeleteCollaborator)
  599. }, reqToken())
  600. m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), reqRepoReader(models.UnitTypeCode), repo.GetRawFile)
  601. m.Get("/archive/*", reqRepoReader(models.UnitTypeCode), repo.GetArchive)
  602. m.Combo("/forks").Get(repo.ListForks).
  603. Post(reqToken(), reqRepoReader(models.UnitTypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
  604. m.Group("/branches", func() {
  605. m.Get("", repo.ListBranches)
  606. m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
  607. m.Delete("/*", reqRepoWriter(models.UnitTypeCode), context.RepoRefByType(context.RepoRefBranch), repo.DeleteBranch)
  608. m.Post("", reqRepoWriter(models.UnitTypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch)
  609. }, reqRepoReader(models.UnitTypeCode))
  610. m.Group("/branch_protections", func() {
  611. m.Get("", repo.ListBranchProtections)
  612. m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection)
  613. m.Group("/:name", func() {
  614. m.Get("", repo.GetBranchProtection)
  615. m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection)
  616. m.Delete("", repo.DeleteBranchProtection)
  617. })
  618. }, reqToken(), reqAdmin())
  619. m.Group("/tags", func() {
  620. m.Get("", repo.ListTags)
  621. }, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(true))
  622. m.Group("/keys", func() {
  623. m.Combo("").Get(repo.ListDeployKeys).
  624. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  625. m.Combo("/:id").Get(repo.GetDeployKey).
  626. Delete(repo.DeleteDeploykey)
  627. }, reqToken(), reqAdmin())
  628. m.Group("/times", func() {
  629. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  630. m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)
  631. }, mustEnableIssues, reqToken())
  632. m.Group("/issues", func() {
  633. m.Combo("").Get(repo.ListIssues).
  634. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue)
  635. m.Group("/comments", func() {
  636. m.Get("", repo.ListRepoIssueComments)
  637. m.Group("/:id", func() {
  638. m.Combo("").
  639. Get(repo.GetIssueComment).
  640. Patch(mustNotBeArchived, reqToken(), bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  641. Delete(reqToken(), repo.DeleteIssueComment)
  642. m.Combo("/reactions").
  643. Get(repo.GetIssueCommentReactions).
  644. Post(bind(api.EditReactionOption{}), reqToken(), repo.PostIssueCommentReaction).
  645. Delete(bind(api.EditReactionOption{}), reqToken(), repo.DeleteIssueCommentReaction)
  646. })
  647. })
  648. m.Group("/:index", func() {
  649. m.Combo("").Get(repo.GetIssue).
  650. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  651. m.Group("/comments", func() {
  652. m.Combo("").Get(repo.ListIssueComments).
  653. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  654. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  655. Delete(repo.DeleteIssueCommentDeprecated)
  656. })
  657. m.Group("/labels", func() {
  658. m.Combo("").Get(repo.ListIssueLabels).
  659. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  660. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  661. Delete(reqToken(), repo.ClearIssueLabels)
  662. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  663. })
  664. m.Group("/times", func() {
  665. m.Combo("").
  666. Get(repo.ListTrackedTimes).
  667. Post(bind(api.AddTimeOption{}), repo.AddTime).
  668. Delete(repo.ResetIssueTime)
  669. m.Delete("/:id", repo.DeleteTime)
  670. }, reqToken())
  671. m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  672. m.Group("/stopwatch", func() {
  673. m.Post("/start", reqToken(), repo.StartIssueStopwatch)
  674. m.Post("/stop", reqToken(), repo.StopIssueStopwatch)
  675. m.Delete("/delete", reqToken(), repo.DeleteIssueStopwatch)
  676. })
  677. m.Group("/subscriptions", func() {
  678. m.Get("", repo.GetIssueSubscribers)
  679. m.Get("/check", reqToken(), repo.CheckIssueSubscription)
  680. m.Put("/:user", reqToken(), repo.AddIssueSubscription)
  681. m.Delete("/:user", reqToken(), repo.DelIssueSubscription)
  682. })
  683. m.Combo("/reactions").
  684. Get(repo.GetIssueReactions).
  685. Post(bind(api.EditReactionOption{}), reqToken(), repo.PostIssueReaction).
  686. Delete(bind(api.EditReactionOption{}), reqToken(), repo.DeleteIssueReaction)
  687. })
  688. }, mustEnableIssuesOrPulls)
  689. m.Group("/labels", func() {
  690. m.Combo("").Get(repo.ListLabels).
  691. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel)
  692. m.Combo("/:id").Get(repo.GetLabel).
  693. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel).
  694. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteLabel)
  695. })
  696. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  697. m.Post("/markdown/raw", misc.MarkdownRaw)
  698. m.Group("/milestones", func() {
  699. m.Combo("").Get(repo.ListMilestones).
  700. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  701. m.Combo("/:id").Get(repo.GetMilestone).
  702. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  703. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteMilestone)
  704. })
  705. m.Get("/stargazers", repo.ListStargazers)
  706. m.Get("/subscribers", repo.ListSubscribers)
  707. m.Group("/subscription", func() {
  708. m.Get("", user.IsWatching)
  709. m.Put("", reqToken(), user.Watch)
  710. m.Delete("", reqToken(), user.Unwatch)
  711. })
  712. m.Group("/releases", func() {
  713. m.Combo("").Get(repo.ListReleases).
  714. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  715. m.Group("/:id", func() {
  716. m.Combo("").Get(repo.GetRelease).
  717. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.EditReleaseOption{}), repo.EditRelease).
  718. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteRelease)
  719. m.Group("/assets", func() {
  720. m.Combo("").Get(repo.ListReleaseAttachments).
  721. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.CreateReleaseAttachment)
  722. m.Combo("/:asset").Get(repo.GetReleaseAttachment).
  723. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  724. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteReleaseAttachment)
  725. })
  726. })
  727. }, reqRepoReader(models.UnitTypeReleases))
  728. m.Post("/mirror-sync", reqToken(), reqRepoWriter(models.UnitTypeCode), repo.MirrorSync)
  729. m.Get("/editorconfig/:filename", context.RepoRef(), reqRepoReader(models.UnitTypeCode), repo.GetEditorconfig)
  730. m.Group("/pulls", func() {
  731. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  732. Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  733. m.Group("/:index", func() {
  734. m.Combo("").Get(repo.GetPullRequest).
  735. Patch(reqToken(), reqRepoWriter(models.UnitTypePullRequests), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  736. m.Get(".diff", repo.DownloadPullDiff)
  737. m.Get(".patch", repo.DownloadPullPatch)
  738. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  739. Post(reqToken(), mustNotBeArchived, bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
  740. m.Group("/reviews", func() {
  741. m.Combo("").
  742. Get(repo.ListPullReviews).
  743. Post(reqToken(), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview)
  744. m.Group("/:id", func() {
  745. m.Combo("").
  746. Get(repo.GetPullReview).
  747. Delete(reqToken(), repo.DeletePullReview).
  748. Post(reqToken(), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview)
  749. m.Combo("/comments").
  750. Get(repo.GetPullReviewComments)
  751. })
  752. })
  753. })
  754. }, mustAllowPulls, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(false))
  755. m.Group("/statuses", func() {
  756. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  757. Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  758. }, reqRepoReader(models.UnitTypeCode))
  759. m.Group("/commits", func() {
  760. m.Get("", repo.GetAllCommits)
  761. m.Group("/:ref", func() {
  762. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  763. m.Get("/statuses", repo.GetCommitStatusesByRef)
  764. })
  765. }, reqRepoReader(models.UnitTypeCode))
  766. m.Group("/git", func() {
  767. m.Group("/commits", func() {
  768. m.Get("/:sha", repo.GetSingleCommit)
  769. })
  770. m.Get("/refs", repo.GetGitAllRefs)
  771. m.Get("/refs/*", repo.GetGitRefs)
  772. m.Get("/trees/:sha", context.RepoRef(), repo.GetTree)
  773. m.Get("/blobs/:sha", context.RepoRef(), repo.GetBlob)
  774. m.Get("/tags/:sha", context.RepoRef(), repo.GetTag)
  775. }, reqRepoReader(models.UnitTypeCode))
  776. m.Group("/contents", func() {
  777. m.Get("", repo.GetContentsList)
  778. m.Get("/*", repo.GetContents)
  779. m.Group("/*", func() {
  780. m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile)
  781. m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile)
  782. m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile)
  783. }, reqRepoWriter(models.UnitTypeCode), reqToken())
  784. }, reqRepoReader(models.UnitTypeCode))
  785. m.Get("/signing-key.gpg", misc.SigningKey)
  786. m.Group("/topics", func() {
  787. m.Combo("").Get(repo.ListTopics).
  788. Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics)
  789. m.Group("/:topic", func() {
  790. m.Combo("").Put(reqToken(), repo.AddTopic).
  791. Delete(reqToken(), repo.DeleteTopic)
  792. }, reqAdmin())
  793. }, reqAnyRepoReader())
  794. m.Get("/languages", reqRepoReader(models.UnitTypeCode), repo.GetLanguages)
  795. }, repoAssignment())
  796. })
  797. // Organizations
  798. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  799. m.Get("/users/:username/orgs", org.ListUserOrgs)
  800. m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
  801. m.Get("/orgs", org.GetAll)
  802. m.Group("/orgs/:org", func() {
  803. m.Combo("").Get(org.Get).
  804. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit).
  805. Delete(reqToken(), reqOrgOwnership(), org.Delete)
  806. m.Combo("/repos").Get(user.ListOrgRepos).
  807. Post(reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  808. m.Group("/members", func() {
  809. m.Get("", org.ListMembers)
  810. m.Combo("/:username").Get(org.IsMember).
  811. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  812. })
  813. m.Group("/public_members", func() {
  814. m.Get("", org.ListPublicMembers)
  815. m.Combo("/:username").Get(org.IsPublicMember).
  816. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  817. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  818. })
  819. m.Group("/teams", func() {
  820. m.Combo("", reqToken()).Get(org.ListTeams).
  821. Post(reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam)
  822. m.Get("/search", org.SearchTeam)
  823. }, reqOrgMembership())
  824. m.Group("/labels", func() {
  825. m.Get("", org.ListLabels)
  826. m.Post("", reqToken(), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel)
  827. m.Combo("/:id").Get(org.GetLabel).
  828. Patch(reqToken(), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel).
  829. Delete(reqToken(), reqOrgOwnership(), org.DeleteLabel)
  830. })
  831. m.Group("/hooks", func() {
  832. m.Combo("").Get(org.ListHooks).
  833. Post(bind(api.CreateHookOption{}), org.CreateHook)
  834. m.Combo("/:id").Get(org.GetHook).
  835. Patch(bind(api.EditHookOption{}), org.EditHook).
  836. Delete(org.DeleteHook)
  837. }, reqToken(), reqOrgOwnership())
  838. }, orgAssignment(true))
  839. m.Group("/teams/:teamid", func() {
  840. m.Combo("").Get(org.GetTeam).
  841. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  842. Delete(reqOrgOwnership(), org.DeleteTeam)
  843. m.Group("/members", func() {
  844. m.Get("", org.GetTeamMembers)
  845. m.Combo("/:username").
  846. Get(org.GetTeamMember).
  847. Put(reqOrgOwnership(), org.AddTeamMember).
  848. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  849. })
  850. m.Group("/repos", func() {
  851. m.Get("", org.GetTeamRepos)
  852. m.Combo("/:org/:reponame").
  853. Put(org.AddTeamRepository).
  854. Delete(org.RemoveTeamRepository)
  855. })
  856. }, orgAssignment(false, true), reqToken(), reqTeamMembership())
  857. m.Any("/*", func(ctx *context.APIContext) {
  858. ctx.NotFound()
  859. })
  860. m.Group("/admin", func() {
  861. m.Get("/orgs", admin.GetAllOrgs)
  862. m.Group("/users", func() {
  863. m.Get("", admin.GetAllUsers)
  864. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  865. m.Group("/:username", func() {
  866. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  867. Delete(admin.DeleteUser)
  868. m.Group("/keys", func() {
  869. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  870. m.Delete("/:id", admin.DeleteUserPublicKey)
  871. })
  872. m.Get("/orgs", org.ListUserOrgs)
  873. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  874. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  875. })
  876. })
  877. }, reqToken(), reqSiteAdmin())
  878. m.Group("/topics", func() {
  879. m.Get("/search", repo.TopicSearch)
  880. })
  881. }, securityHeaders(), context.APIContexter(), sudo())
  882. }
  883. func securityHeaders() macaron.Handler {
  884. return func(ctx *macaron.Context) {
  885. ctx.Resp.Before(func(w macaron.ResponseWriter) {
  886. // CORB: https://www.chromium.org/Home/chromium-security/corb-for-developers
  887. // http://stackoverflow.com/a/3146618/244009
  888. w.Header().Set("x-content-type-options", "nosniff")
  889. })
  890. }
  891. }