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 30KB

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