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

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