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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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.Combo("/threads/:id").
  479. Get(notify.GetThread).
  480. Patch(notify.ReadThread)
  481. }, reqToken())
  482. // Users
  483. m.Group("/users", func() {
  484. m.Get("/search", user.Search)
  485. m.Group("/:username", func() {
  486. m.Get("", user.GetInfo)
  487. m.Get("/heatmap", mustEnableUserHeatmap, user.GetUserHeatmapData)
  488. m.Get("/repos", user.ListUserRepos)
  489. m.Group("/tokens", func() {
  490. m.Combo("").Get(user.ListAccessTokens).
  491. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  492. m.Combo("/:id").Delete(user.DeleteAccessToken)
  493. }, reqBasicAuth())
  494. })
  495. })
  496. m.Group("/users", func() {
  497. m.Group("/:username", func() {
  498. m.Get("/keys", user.ListPublicKeys)
  499. m.Get("/gpg_keys", user.ListGPGKeys)
  500. m.Get("/followers", user.ListFollowers)
  501. m.Group("/following", func() {
  502. m.Get("", user.ListFollowing)
  503. m.Get("/:target", user.CheckFollowing)
  504. })
  505. m.Get("/starred", user.GetStarredRepos)
  506. m.Get("/subscriptions", user.GetWatchedRepos)
  507. })
  508. }, reqToken())
  509. m.Group("/user", func() {
  510. m.Get("", user.GetAuthenticatedUser)
  511. m.Combo("/emails").Get(user.ListEmails).
  512. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  513. Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)
  514. m.Get("/followers", user.ListMyFollowers)
  515. m.Group("/following", func() {
  516. m.Get("", user.ListMyFollowing)
  517. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  518. })
  519. m.Group("/keys", func() {
  520. m.Combo("").Get(user.ListMyPublicKeys).
  521. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  522. m.Combo("/:id").Get(user.GetPublicKey).
  523. Delete(user.DeletePublicKey)
  524. })
  525. m.Group("/gpg_keys", func() {
  526. m.Combo("").Get(user.ListMyGPGKeys).
  527. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  528. m.Combo("/:id").Get(user.GetGPGKey).
  529. Delete(user.DeleteGPGKey)
  530. })
  531. m.Combo("/repos").Get(user.ListMyRepos).
  532. Post(bind(api.CreateRepoOption{}), repo.Create)
  533. m.Group("/starred", func() {
  534. m.Get("", user.GetMyStarredRepos)
  535. m.Group("/:username/:reponame", func() {
  536. m.Get("", user.IsStarring)
  537. m.Put("", user.Star)
  538. m.Delete("", user.Unstar)
  539. }, repoAssignment())
  540. })
  541. m.Get("/times", repo.ListMyTrackedTimes)
  542. m.Get("/stopwatches", repo.GetStopwatches)
  543. m.Get("/subscriptions", user.GetMyWatchedRepos)
  544. m.Get("/teams", org.ListUserTeams)
  545. }, reqToken())
  546. // Repositories
  547. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  548. m.Group("/repos", func() {
  549. m.Get("/search", repo.Search)
  550. })
  551. m.Get("/repos/issues/search", repo.SearchIssues)
  552. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  553. m.Group("/repos", func() {
  554. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  555. m.Group("/:username/:reponame", func() {
  556. m.Combo("").Get(reqAnyRepoReader(), repo.Get).
  557. Delete(reqToken(), reqOwner(), repo.Delete).
  558. Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), context.RepoRef(), repo.Edit)
  559. m.Combo("/notifications").
  560. Get(reqToken(), notify.ListRepoNotifications).
  561. Put(reqToken(), notify.ReadRepoNotifications)
  562. m.Group("/hooks", func() {
  563. m.Combo("").Get(repo.ListHooks).
  564. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  565. m.Group("/:id", func() {
  566. m.Combo("").Get(repo.GetHook).
  567. Patch(bind(api.EditHookOption{}), repo.EditHook).
  568. Delete(repo.DeleteHook)
  569. m.Post("/tests", context.RepoRef(), repo.TestHook)
  570. })
  571. m.Group("/git", func() {
  572. m.Combo("").Get(repo.ListGitHooks)
  573. m.Group("/:id", func() {
  574. m.Combo("").Get(repo.GetGitHook).
  575. Patch(bind(api.EditGitHookOption{}), repo.EditGitHook).
  576. Delete(repo.DeleteGitHook)
  577. })
  578. }, reqGitHook(), context.ReferencesGitRepo(true))
  579. }, reqToken(), reqAdmin())
  580. m.Group("/collaborators", func() {
  581. m.Get("", repo.ListCollaborators)
  582. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  583. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  584. Delete(repo.DeleteCollaborator)
  585. }, reqToken(), reqAdmin())
  586. m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), reqRepoReader(models.UnitTypeCode), repo.GetRawFile)
  587. m.Get("/archive/*", reqRepoReader(models.UnitTypeCode), repo.GetArchive)
  588. m.Combo("/forks").Get(repo.ListForks).
  589. Post(reqToken(), reqRepoReader(models.UnitTypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
  590. m.Group("/branches", func() {
  591. m.Get("", repo.ListBranches)
  592. m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
  593. }, reqRepoReader(models.UnitTypeCode))
  594. m.Group("/tags", func() {
  595. m.Get("", repo.ListTags)
  596. }, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(true))
  597. m.Group("/keys", func() {
  598. m.Combo("").Get(repo.ListDeployKeys).
  599. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  600. m.Combo("/:id").Get(repo.GetDeployKey).
  601. Delete(repo.DeleteDeploykey)
  602. }, reqToken(), reqAdmin())
  603. m.Group("/times", func() {
  604. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  605. m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)
  606. }, mustEnableIssues, reqToken())
  607. m.Group("/issues", func() {
  608. m.Combo("").Get(repo.ListIssues).
  609. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue)
  610. m.Group("/comments", func() {
  611. m.Get("", repo.ListRepoIssueComments)
  612. m.Group("/:id", func() {
  613. m.Combo("").
  614. Get(repo.GetIssueComment).
  615. Patch(mustNotBeArchived, reqToken(), bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  616. Delete(reqToken(), repo.DeleteIssueComment)
  617. m.Combo("/reactions").
  618. Get(repo.GetIssueCommentReactions).
  619. Post(bind(api.EditReactionOption{}), reqToken(), repo.PostIssueCommentReaction).
  620. Delete(bind(api.EditReactionOption{}), reqToken(), repo.DeleteIssueCommentReaction)
  621. })
  622. })
  623. m.Group("/:index", func() {
  624. m.Combo("").Get(repo.GetIssue).
  625. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  626. m.Group("/comments", func() {
  627. m.Combo("").Get(repo.ListIssueComments).
  628. Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  629. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  630. Delete(repo.DeleteIssueCommentDeprecated)
  631. })
  632. m.Group("/labels", func() {
  633. m.Combo("").Get(repo.ListIssueLabels).
  634. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  635. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  636. Delete(reqToken(), repo.ClearIssueLabels)
  637. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  638. })
  639. m.Group("/times", func() {
  640. m.Combo("").
  641. Get(repo.ListTrackedTimes).
  642. Post(bind(api.AddTimeOption{}), repo.AddTime).
  643. Delete(repo.ResetIssueTime)
  644. m.Delete("/:id", repo.DeleteTime)
  645. }, reqToken())
  646. m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  647. m.Group("/stopwatch", func() {
  648. m.Post("/start", reqToken(), repo.StartIssueStopwatch)
  649. m.Post("/stop", reqToken(), repo.StopIssueStopwatch)
  650. m.Delete("/delete", reqToken(), repo.DeleteIssueStopwatch)
  651. })
  652. m.Group("/subscriptions", func() {
  653. m.Get("", repo.GetIssueSubscribers)
  654. m.Put("/:user", reqToken(), repo.AddIssueSubscription)
  655. m.Delete("/:user", reqToken(), repo.DelIssueSubscription)
  656. })
  657. m.Combo("/reactions").
  658. Get(repo.GetIssueReactions).
  659. Post(bind(api.EditReactionOption{}), reqToken(), repo.PostIssueReaction).
  660. Delete(bind(api.EditReactionOption{}), reqToken(), repo.DeleteIssueReaction)
  661. })
  662. }, mustEnableIssuesOrPulls)
  663. m.Group("/labels", func() {
  664. m.Combo("").Get(repo.ListLabels).
  665. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel)
  666. m.Combo("/:id").Get(repo.GetLabel).
  667. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel).
  668. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteLabel)
  669. })
  670. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  671. m.Post("/markdown/raw", misc.MarkdownRaw)
  672. m.Group("/milestones", func() {
  673. m.Combo("").Get(repo.ListMilestones).
  674. Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  675. m.Combo("/:id").Get(repo.GetMilestone).
  676. Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  677. Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteMilestone)
  678. })
  679. m.Get("/stargazers", repo.ListStargazers)
  680. m.Get("/subscribers", repo.ListSubscribers)
  681. m.Group("/subscription", func() {
  682. m.Get("", user.IsWatching)
  683. m.Put("", reqToken(), user.Watch)
  684. m.Delete("", reqToken(), user.Unwatch)
  685. })
  686. m.Group("/releases", func() {
  687. m.Combo("").Get(repo.ListReleases).
  688. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  689. m.Group("/:id", func() {
  690. m.Combo("").Get(repo.GetRelease).
  691. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.EditReleaseOption{}), repo.EditRelease).
  692. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteRelease)
  693. m.Group("/assets", func() {
  694. m.Combo("").Get(repo.ListReleaseAttachments).
  695. Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.CreateReleaseAttachment)
  696. m.Combo("/:asset").Get(repo.GetReleaseAttachment).
  697. Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  698. Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteReleaseAttachment)
  699. })
  700. })
  701. }, reqRepoReader(models.UnitTypeReleases))
  702. m.Post("/mirror-sync", reqToken(), reqRepoWriter(models.UnitTypeCode), repo.MirrorSync)
  703. m.Get("/editorconfig/:filename", context.RepoRef(), reqRepoReader(models.UnitTypeCode), repo.GetEditorconfig)
  704. m.Group("/pulls", func() {
  705. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  706. Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  707. m.Group("/:index", func() {
  708. m.Combo("").Get(repo.GetPullRequest).
  709. Patch(reqToken(), reqRepoWriter(models.UnitTypePullRequests), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  710. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  711. Post(reqToken(), mustNotBeArchived, reqRepoWriter(models.UnitTypePullRequests), bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
  712. })
  713. }, mustAllowPulls, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(false))
  714. m.Group("/statuses", func() {
  715. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  716. Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  717. }, reqRepoReader(models.UnitTypeCode))
  718. m.Group("/commits", func() {
  719. m.Get("", repo.GetAllCommits)
  720. m.Group("/:ref", func() {
  721. // TODO: Add m.Get("") for single commit (https://developer.github.com/v3/repos/commits/#get-a-single-commit)
  722. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  723. m.Get("/statuses", repo.GetCommitStatusesByRef)
  724. })
  725. }, reqRepoReader(models.UnitTypeCode))
  726. m.Group("/git", func() {
  727. m.Group("/commits", func() {
  728. m.Get("/:sha", repo.GetSingleCommit)
  729. })
  730. m.Get("/refs", repo.GetGitAllRefs)
  731. m.Get("/refs/*", repo.GetGitRefs)
  732. m.Get("/trees/:sha", context.RepoRef(), repo.GetTree)
  733. m.Get("/blobs/:sha", context.RepoRef(), repo.GetBlob)
  734. m.Get("/tags/:sha", context.RepoRef(), repo.GetTag)
  735. }, reqRepoReader(models.UnitTypeCode))
  736. m.Group("/contents", func() {
  737. m.Get("", repo.GetContentsList)
  738. m.Get("/*", repo.GetContents)
  739. m.Group("/*", func() {
  740. m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile)
  741. m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile)
  742. m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile)
  743. }, reqRepoWriter(models.UnitTypeCode), reqToken())
  744. }, reqRepoReader(models.UnitTypeCode))
  745. m.Get("/signing-key.gpg", misc.SigningKey)
  746. m.Group("/topics", func() {
  747. m.Combo("").Get(repo.ListTopics).
  748. Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics)
  749. m.Group("/:topic", func() {
  750. m.Combo("").Put(reqToken(), repo.AddTopic).
  751. Delete(reqToken(), repo.DeleteTopic)
  752. }, reqAdmin())
  753. }, reqAnyRepoReader())
  754. }, repoAssignment())
  755. })
  756. // Organizations
  757. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  758. m.Get("/users/:username/orgs", org.ListUserOrgs)
  759. m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
  760. m.Group("/orgs/:orgname", func() {
  761. m.Get("/repos", user.ListOrgRepos)
  762. m.Combo("").Get(org.Get).
  763. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit).
  764. Delete(reqToken(), reqOrgOwnership(), org.Delete)
  765. m.Group("/members", func() {
  766. m.Get("", org.ListMembers)
  767. m.Combo("/:username").Get(org.IsMember).
  768. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  769. })
  770. m.Group("/public_members", func() {
  771. m.Get("", org.ListPublicMembers)
  772. m.Combo("/:username").Get(org.IsPublicMember).
  773. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  774. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  775. })
  776. m.Group("/teams", func() {
  777. m.Combo("", reqToken()).Get(org.ListTeams).
  778. Post(reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam)
  779. m.Get("/search", org.SearchTeam)
  780. }, reqOrgMembership())
  781. m.Group("/hooks", func() {
  782. m.Combo("").Get(org.ListHooks).
  783. Post(bind(api.CreateHookOption{}), org.CreateHook)
  784. m.Combo("/:id").Get(org.GetHook).
  785. Patch(bind(api.EditHookOption{}), org.EditHook).
  786. Delete(org.DeleteHook)
  787. }, reqToken(), reqOrgOwnership())
  788. }, orgAssignment(true))
  789. m.Group("/teams/:teamid", func() {
  790. m.Combo("").Get(org.GetTeam).
  791. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  792. Delete(reqOrgOwnership(), org.DeleteTeam)
  793. m.Group("/members", func() {
  794. m.Get("", org.GetTeamMembers)
  795. m.Combo("/:username").
  796. Get(org.GetTeamMember).
  797. Put(reqOrgOwnership(), org.AddTeamMember).
  798. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  799. })
  800. m.Group("/repos", func() {
  801. m.Get("", org.GetTeamRepos)
  802. m.Combo("/:orgname/:reponame").
  803. Put(org.AddTeamRepository).
  804. Delete(org.RemoveTeamRepository)
  805. })
  806. }, orgAssignment(false, true), reqToken(), reqTeamMembership())
  807. m.Any("/*", func(ctx *context.APIContext) {
  808. ctx.NotFound()
  809. })
  810. m.Group("/admin", func() {
  811. m.Get("/orgs", admin.GetAllOrgs)
  812. m.Group("/users", func() {
  813. m.Get("", admin.GetAllUsers)
  814. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  815. m.Group("/:username", func() {
  816. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  817. Delete(admin.DeleteUser)
  818. m.Group("/keys", func() {
  819. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  820. m.Delete("/:id", admin.DeleteUserPublicKey)
  821. })
  822. m.Get("/orgs", org.ListUserOrgs)
  823. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  824. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  825. })
  826. })
  827. }, reqToken(), reqSiteAdmin())
  828. m.Group("/topics", func() {
  829. m.Get("/search", repo.TopicSearch)
  830. })
  831. }, securityHeaders(), context.APIContexter(), sudo())
  832. }
  833. func securityHeaders() macaron.Handler {
  834. return func(ctx *macaron.Context) {
  835. ctx.Resp.Before(func(w macaron.ResponseWriter) {
  836. // CORB: https://www.chromium.org/Home/chromium-security/corb-for-developers
  837. // http://stackoverflow.com/a/3146618/244009
  838. w.Header().Set("x-content-type-options", "nosniff")
  839. })
  840. }
  841. }