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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. // Package v1 Gitea API.
  5. //
  6. // This documentation describes the Gitea API.
  7. //
  8. // Schemes: http, https
  9. // BasePath: /api/v1
  10. // Version: {{AppVer | JSEscape | Safe}}
  11. // License: MIT http://opensource.org/licenses/MIT
  12. //
  13. // Consumes:
  14. // - application/json
  15. // - text/plain
  16. //
  17. // Produces:
  18. // - application/json
  19. // - text/html
  20. //
  21. // Security:
  22. // - BasicAuth :
  23. // - Token :
  24. // - AccessToken :
  25. // - AuthorizationHeaderToken :
  26. // - SudoParam :
  27. // - SudoHeader :
  28. // - TOTPHeader :
  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. // TOTPHeader:
  57. // type: apiKey
  58. // name: X-GITEA-OTP
  59. // in: header
  60. // description: Must be used in combination with BasicAuth if two-factor authentication is enabled.
  61. //
  62. // swagger:meta
  63. package v1
  64. import (
  65. gocontext "context"
  66. "fmt"
  67. "net/http"
  68. "strings"
  69. actions_model "code.gitea.io/gitea/models/actions"
  70. auth_model "code.gitea.io/gitea/models/auth"
  71. "code.gitea.io/gitea/models/organization"
  72. "code.gitea.io/gitea/models/perm"
  73. access_model "code.gitea.io/gitea/models/perm/access"
  74. repo_model "code.gitea.io/gitea/models/repo"
  75. "code.gitea.io/gitea/models/unit"
  76. user_model "code.gitea.io/gitea/models/user"
  77. "code.gitea.io/gitea/modules/context"
  78. "code.gitea.io/gitea/modules/log"
  79. "code.gitea.io/gitea/modules/setting"
  80. api "code.gitea.io/gitea/modules/structs"
  81. "code.gitea.io/gitea/modules/web"
  82. "code.gitea.io/gitea/routers/api/v1/activitypub"
  83. "code.gitea.io/gitea/routers/api/v1/admin"
  84. "code.gitea.io/gitea/routers/api/v1/misc"
  85. "code.gitea.io/gitea/routers/api/v1/notify"
  86. "code.gitea.io/gitea/routers/api/v1/org"
  87. "code.gitea.io/gitea/routers/api/v1/packages"
  88. "code.gitea.io/gitea/routers/api/v1/repo"
  89. "code.gitea.io/gitea/routers/api/v1/settings"
  90. "code.gitea.io/gitea/routers/api/v1/user"
  91. "code.gitea.io/gitea/services/auth"
  92. context_service "code.gitea.io/gitea/services/context"
  93. "code.gitea.io/gitea/services/forms"
  94. _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
  95. "gitea.com/go-chi/binding"
  96. "github.com/go-chi/cors"
  97. )
  98. func sudo() func(ctx *context.APIContext) {
  99. return func(ctx *context.APIContext) {
  100. sudo := ctx.FormString("sudo")
  101. if len(sudo) == 0 {
  102. sudo = ctx.Req.Header.Get("Sudo")
  103. }
  104. if len(sudo) > 0 {
  105. if ctx.IsSigned && ctx.Doer.IsAdmin {
  106. user, err := user_model.GetUserByName(ctx, sudo)
  107. if err != nil {
  108. if user_model.IsErrUserNotExist(err) {
  109. ctx.NotFound()
  110. } else {
  111. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  112. }
  113. return
  114. }
  115. log.Trace("Sudo from (%s) to: %s", ctx.Doer.Name, user.Name)
  116. ctx.Doer = user
  117. } else {
  118. ctx.JSON(http.StatusForbidden, map[string]string{
  119. "message": "Only administrators allowed to sudo.",
  120. })
  121. return
  122. }
  123. }
  124. }
  125. }
  126. func repoAssignment() func(ctx *context.APIContext) {
  127. return func(ctx *context.APIContext) {
  128. userName := ctx.Params("username")
  129. repoName := ctx.Params("reponame")
  130. var (
  131. owner *user_model.User
  132. err error
  133. )
  134. // Check if the user is the same as the repository owner.
  135. if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) {
  136. owner = ctx.Doer
  137. } else {
  138. owner, err = user_model.GetUserByName(ctx, userName)
  139. if err != nil {
  140. if user_model.IsErrUserNotExist(err) {
  141. if redirectUserID, err := user_model.LookupUserRedirect(userName); err == nil {
  142. context.RedirectToUser(ctx.Context, userName, redirectUserID)
  143. } else if user_model.IsErrUserRedirectNotExist(err) {
  144. ctx.NotFound("GetUserByName", err)
  145. } else {
  146. ctx.Error(http.StatusInternalServerError, "LookupUserRedirect", err)
  147. }
  148. } else {
  149. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  150. }
  151. return
  152. }
  153. }
  154. ctx.Repo.Owner = owner
  155. ctx.ContextUser = owner
  156. // Get repository.
  157. repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
  158. if err != nil {
  159. if repo_model.IsErrRepoNotExist(err) {
  160. redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
  161. if err == nil {
  162. context.RedirectToRepo(ctx.Context, redirectRepoID)
  163. } else if repo_model.IsErrRedirectNotExist(err) {
  164. ctx.NotFound()
  165. } else {
  166. ctx.Error(http.StatusInternalServerError, "LookupRepoRedirect", err)
  167. }
  168. } else {
  169. ctx.Error(http.StatusInternalServerError, "GetRepositoryByName", err)
  170. }
  171. return
  172. }
  173. repo.Owner = owner
  174. ctx.Repo.Repository = repo
  175. if ctx.Doer != nil && ctx.Doer.ID == user_model.ActionsUserID {
  176. taskID := ctx.Data["ActionsTaskID"].(int64)
  177. task, err := actions_model.GetTaskByID(ctx, taskID)
  178. if err != nil {
  179. ctx.Error(http.StatusInternalServerError, "actions_model.GetTaskByID", err)
  180. return
  181. }
  182. if task.RepoID != repo.ID {
  183. ctx.NotFound()
  184. return
  185. }
  186. if task.IsForkPullRequest {
  187. ctx.Repo.Permission.AccessMode = perm.AccessModeRead
  188. } else {
  189. ctx.Repo.Permission.AccessMode = perm.AccessModeWrite
  190. }
  191. if err := ctx.Repo.Repository.LoadUnits(ctx); err != nil {
  192. ctx.Error(http.StatusInternalServerError, "LoadUnits", err)
  193. return
  194. }
  195. ctx.Repo.Permission.Units = ctx.Repo.Repository.Units
  196. ctx.Repo.Permission.UnitsMode = make(map[unit.Type]perm.AccessMode)
  197. for _, u := range ctx.Repo.Repository.Units {
  198. ctx.Repo.Permission.UnitsMode[u.Type] = ctx.Repo.Permission.AccessMode
  199. }
  200. } else {
  201. ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
  202. if err != nil {
  203. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  204. return
  205. }
  206. }
  207. if !ctx.Repo.HasAccess() {
  208. ctx.NotFound()
  209. return
  210. }
  211. }
  212. }
  213. func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) {
  214. return func(ctx *context.APIContext) {
  215. if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
  216. ctx.Error(http.StatusForbidden, "reqPackageAccess", "user should have specific permission or be a site admin")
  217. return
  218. }
  219. }
  220. }
  221. // Contexter middleware already checks token for user sign in process.
  222. func reqToken(requiredScope auth_model.AccessTokenScope) func(ctx *context.APIContext) {
  223. return func(ctx *context.APIContext) {
  224. // If actions token is present
  225. if true == ctx.Data["IsActionsToken"] {
  226. return
  227. }
  228. // If OAuth2 token is present
  229. if _, ok := ctx.Data["ApiTokenScope"]; ctx.Data["IsApiToken"] == true && ok {
  230. // no scope required
  231. if requiredScope == "" {
  232. return
  233. }
  234. // check scope
  235. scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)
  236. allow, err := scope.HasScope(requiredScope)
  237. if err != nil {
  238. ctx.Error(http.StatusForbidden, "reqToken", "parsing token failed: "+err.Error())
  239. return
  240. }
  241. if allow {
  242. return
  243. }
  244. // if requires 'repo' scope, but only has 'public_repo' scope, allow it only if the repo is public
  245. if requiredScope == auth_model.AccessTokenScopeRepo {
  246. if allowPublicRepo, err := scope.HasScope(auth_model.AccessTokenScopePublicRepo); err == nil && allowPublicRepo {
  247. if ctx.Repo.Repository != nil && !ctx.Repo.Repository.IsPrivate {
  248. return
  249. }
  250. }
  251. }
  252. ctx.Error(http.StatusForbidden, "reqToken", "token does not have required scope: "+requiredScope)
  253. return
  254. }
  255. if ctx.Context.IsBasicAuth {
  256. ctx.CheckForOTP()
  257. return
  258. }
  259. if ctx.IsSigned {
  260. return
  261. }
  262. ctx.Error(http.StatusUnauthorized, "reqToken", "token is required")
  263. }
  264. }
  265. func reqExploreSignIn() func(ctx *context.APIContext) {
  266. return func(ctx *context.APIContext) {
  267. if setting.Service.Explore.RequireSigninView && !ctx.IsSigned {
  268. ctx.Error(http.StatusUnauthorized, "reqExploreSignIn", "you must be signed in to search for users")
  269. }
  270. }
  271. }
  272. func reqBasicAuth() func(ctx *context.APIContext) {
  273. return func(ctx *context.APIContext) {
  274. if !ctx.Context.IsBasicAuth {
  275. ctx.Error(http.StatusUnauthorized, "reqBasicAuth", "auth required")
  276. return
  277. }
  278. ctx.CheckForOTP()
  279. }
  280. }
  281. // reqSiteAdmin user should be the site admin
  282. func reqSiteAdmin() func(ctx *context.APIContext) {
  283. return func(ctx *context.APIContext) {
  284. if !ctx.IsUserSiteAdmin() {
  285. ctx.Error(http.StatusForbidden, "reqSiteAdmin", "user should be the site admin")
  286. return
  287. }
  288. }
  289. }
  290. // reqOwner user should be the owner of the repo or site admin.
  291. func reqOwner() func(ctx *context.APIContext) {
  292. return func(ctx *context.APIContext) {
  293. if !ctx.IsUserRepoOwner() && !ctx.IsUserSiteAdmin() {
  294. ctx.Error(http.StatusForbidden, "reqOwner", "user should be the owner of the repo")
  295. return
  296. }
  297. }
  298. }
  299. // reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin
  300. func reqAdmin() func(ctx *context.APIContext) {
  301. return func(ctx *context.APIContext) {
  302. if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  303. ctx.Error(http.StatusForbidden, "reqAdmin", "user should be an owner or a collaborator with admin write of a repository")
  304. return
  305. }
  306. }
  307. }
  308. // reqRepoWriter user should have a permission to write to a repo, or be a site admin
  309. func reqRepoWriter(unitTypes ...unit.Type) func(ctx *context.APIContext) {
  310. return func(ctx *context.APIContext) {
  311. if !ctx.IsUserRepoWriter(unitTypes) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  312. ctx.Error(http.StatusForbidden, "reqRepoWriter", "user should have a permission to write to a repo")
  313. return
  314. }
  315. }
  316. }
  317. // reqRepoBranchWriter user should have a permission to write to a branch, or be a site admin
  318. func reqRepoBranchWriter(ctx *context.APIContext) {
  319. options, ok := web.GetForm(ctx).(api.FileOptionInterface)
  320. if !ok || (!ctx.Repo.CanWriteToBranch(ctx.Doer, options.Branch()) && !ctx.IsUserSiteAdmin()) {
  321. ctx.Error(http.StatusForbidden, "reqRepoBranchWriter", "user should have a permission to write to this branch")
  322. return
  323. }
  324. }
  325. // reqRepoReader user should have specific read permission or be a repo admin or a site admin
  326. func reqRepoReader(unitType unit.Type) func(ctx *context.APIContext) {
  327. return func(ctx *context.APIContext) {
  328. if !ctx.IsUserRepoReaderSpecific(unitType) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
  329. ctx.Error(http.StatusForbidden, "reqRepoReader", "user should have specific read permission or be a repo admin or a site admin")
  330. return
  331. }
  332. }
  333. }
  334. // reqAnyRepoReader user should have any permission to read repository or permissions of site admin
  335. func reqAnyRepoReader() func(ctx *context.APIContext) {
  336. return func(ctx *context.APIContext) {
  337. if !ctx.IsUserRepoReaderAny() && !ctx.IsUserSiteAdmin() {
  338. ctx.Error(http.StatusForbidden, "reqAnyRepoReader", "user should have any permission to read repository or permissions of site admin")
  339. return
  340. }
  341. }
  342. }
  343. // reqOrgOwnership user should be an organization owner, or a site admin
  344. func reqOrgOwnership() func(ctx *context.APIContext) {
  345. return func(ctx *context.APIContext) {
  346. if ctx.Context.IsUserSiteAdmin() {
  347. return
  348. }
  349. var orgID int64
  350. if ctx.Org.Organization != nil {
  351. orgID = ctx.Org.Organization.ID
  352. } else if ctx.Org.Team != nil {
  353. orgID = ctx.Org.Team.OrgID
  354. } else {
  355. ctx.Error(http.StatusInternalServerError, "", "reqOrgOwnership: unprepared context")
  356. return
  357. }
  358. isOwner, err := organization.IsOrganizationOwner(ctx, orgID, ctx.Doer.ID)
  359. if err != nil {
  360. ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
  361. return
  362. } else if !isOwner {
  363. if ctx.Org.Organization != nil {
  364. ctx.Error(http.StatusForbidden, "", "Must be an organization owner")
  365. } else {
  366. ctx.NotFound()
  367. }
  368. return
  369. }
  370. }
  371. }
  372. // reqTeamMembership user should be an team member, or a site admin
  373. func reqTeamMembership() func(ctx *context.APIContext) {
  374. return func(ctx *context.APIContext) {
  375. if ctx.Context.IsUserSiteAdmin() {
  376. return
  377. }
  378. if ctx.Org.Team == nil {
  379. ctx.Error(http.StatusInternalServerError, "", "reqTeamMembership: unprepared context")
  380. return
  381. }
  382. orgID := ctx.Org.Team.OrgID
  383. isOwner, err := organization.IsOrganizationOwner(ctx, orgID, ctx.Doer.ID)
  384. if err != nil {
  385. ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
  386. return
  387. } else if isOwner {
  388. return
  389. }
  390. if isTeamMember, err := organization.IsTeamMember(ctx, orgID, ctx.Org.Team.ID, ctx.Doer.ID); err != nil {
  391. ctx.Error(http.StatusInternalServerError, "IsTeamMember", err)
  392. return
  393. } else if !isTeamMember {
  394. isOrgMember, err := organization.IsOrganizationMember(ctx, orgID, ctx.Doer.ID)
  395. if err != nil {
  396. ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
  397. } else if isOrgMember {
  398. ctx.Error(http.StatusForbidden, "", "Must be a team member")
  399. } else {
  400. ctx.NotFound()
  401. }
  402. return
  403. }
  404. }
  405. }
  406. // reqOrgMembership user should be an organization member, or a site admin
  407. func reqOrgMembership() func(ctx *context.APIContext) {
  408. return func(ctx *context.APIContext) {
  409. if ctx.Context.IsUserSiteAdmin() {
  410. return
  411. }
  412. var orgID int64
  413. if ctx.Org.Organization != nil {
  414. orgID = ctx.Org.Organization.ID
  415. } else if ctx.Org.Team != nil {
  416. orgID = ctx.Org.Team.OrgID
  417. } else {
  418. ctx.Error(http.StatusInternalServerError, "", "reqOrgMembership: unprepared context")
  419. return
  420. }
  421. if isMember, err := organization.IsOrganizationMember(ctx, orgID, ctx.Doer.ID); err != nil {
  422. ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
  423. return
  424. } else if !isMember {
  425. if ctx.Org.Organization != nil {
  426. ctx.Error(http.StatusForbidden, "", "Must be an organization member")
  427. } else {
  428. ctx.NotFound()
  429. }
  430. return
  431. }
  432. }
  433. }
  434. func reqGitHook() func(ctx *context.APIContext) {
  435. return func(ctx *context.APIContext) {
  436. if !ctx.Doer.CanEditGitHook() {
  437. ctx.Error(http.StatusForbidden, "", "must be allowed to edit Git hooks")
  438. return
  439. }
  440. }
  441. }
  442. // reqWebhooksEnabled requires webhooks to be enabled by admin.
  443. func reqWebhooksEnabled() func(ctx *context.APIContext) {
  444. return func(ctx *context.APIContext) {
  445. if setting.DisableWebhooks {
  446. ctx.Error(http.StatusForbidden, "", "webhooks disabled by administrator")
  447. return
  448. }
  449. }
  450. }
  451. func orgAssignment(args ...bool) func(ctx *context.APIContext) {
  452. var (
  453. assignOrg bool
  454. assignTeam bool
  455. )
  456. if len(args) > 0 {
  457. assignOrg = args[0]
  458. }
  459. if len(args) > 1 {
  460. assignTeam = args[1]
  461. }
  462. return func(ctx *context.APIContext) {
  463. ctx.Org = new(context.APIOrganization)
  464. var err error
  465. if assignOrg {
  466. ctx.Org.Organization, err = organization.GetOrgByName(ctx, ctx.Params(":org"))
  467. if err != nil {
  468. if organization.IsErrOrgNotExist(err) {
  469. redirectUserID, err := user_model.LookupUserRedirect(ctx.Params(":org"))
  470. if err == nil {
  471. context.RedirectToUser(ctx.Context, ctx.Params(":org"), redirectUserID)
  472. } else if user_model.IsErrUserRedirectNotExist(err) {
  473. ctx.NotFound("GetOrgByName", err)
  474. } else {
  475. ctx.Error(http.StatusInternalServerError, "LookupUserRedirect", err)
  476. }
  477. } else {
  478. ctx.Error(http.StatusInternalServerError, "GetOrgByName", err)
  479. }
  480. return
  481. }
  482. ctx.ContextUser = ctx.Org.Organization.AsUser()
  483. }
  484. if assignTeam {
  485. ctx.Org.Team, err = organization.GetTeamByID(ctx, ctx.ParamsInt64(":teamid"))
  486. if err != nil {
  487. if organization.IsErrTeamNotExist(err) {
  488. ctx.NotFound()
  489. } else {
  490. ctx.Error(http.StatusInternalServerError, "GetTeamById", err)
  491. }
  492. return
  493. }
  494. }
  495. }
  496. }
  497. func mustEnableIssues(ctx *context.APIContext) {
  498. if !ctx.Repo.CanRead(unit.TypeIssues) {
  499. if log.IsTrace() {
  500. if ctx.IsSigned {
  501. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  502. "User in Repo has Permissions: %-+v",
  503. ctx.Doer,
  504. unit.TypeIssues,
  505. ctx.Repo.Repository,
  506. ctx.Repo.Permission)
  507. } else {
  508. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  509. "Anonymous user in Repo has Permissions: %-+v",
  510. unit.TypeIssues,
  511. ctx.Repo.Repository,
  512. ctx.Repo.Permission)
  513. }
  514. }
  515. ctx.NotFound()
  516. return
  517. }
  518. }
  519. func mustAllowPulls(ctx *context.APIContext) {
  520. if !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(unit.TypePullRequests)) {
  521. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  522. if ctx.IsSigned {
  523. log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
  524. "User in Repo has Permissions: %-+v",
  525. ctx.Doer,
  526. unit.TypePullRequests,
  527. ctx.Repo.Repository,
  528. ctx.Repo.Permission)
  529. } else {
  530. log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+
  531. "Anonymous user in Repo has Permissions: %-+v",
  532. unit.TypePullRequests,
  533. ctx.Repo.Repository,
  534. ctx.Repo.Permission)
  535. }
  536. }
  537. ctx.NotFound()
  538. return
  539. }
  540. }
  541. func mustEnableIssuesOrPulls(ctx *context.APIContext) {
  542. if !ctx.Repo.CanRead(unit.TypeIssues) &&
  543. !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(unit.TypePullRequests)) {
  544. if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() {
  545. if ctx.IsSigned {
  546. log.Trace("Permission Denied: User %-v cannot read %-v and %-v in Repo %-v\n"+
  547. "User in Repo has Permissions: %-+v",
  548. ctx.Doer,
  549. unit.TypeIssues,
  550. unit.TypePullRequests,
  551. ctx.Repo.Repository,
  552. ctx.Repo.Permission)
  553. } else {
  554. log.Trace("Permission Denied: Anonymous user cannot read %-v and %-v in Repo %-v\n"+
  555. "Anonymous user in Repo has Permissions: %-+v",
  556. unit.TypeIssues,
  557. unit.TypePullRequests,
  558. ctx.Repo.Repository,
  559. ctx.Repo.Permission)
  560. }
  561. }
  562. ctx.NotFound()
  563. return
  564. }
  565. }
  566. func mustEnableWiki(ctx *context.APIContext) {
  567. if !(ctx.Repo.CanRead(unit.TypeWiki)) {
  568. ctx.NotFound()
  569. return
  570. }
  571. }
  572. func mustNotBeArchived(ctx *context.APIContext) {
  573. if ctx.Repo.Repository.IsArchived {
  574. ctx.NotFound()
  575. return
  576. }
  577. }
  578. func mustEnableAttachments(ctx *context.APIContext) {
  579. if !setting.Attachment.Enabled {
  580. ctx.NotFound()
  581. return
  582. }
  583. }
  584. // bind binding an obj to a func(ctx *context.APIContext)
  585. func bind[T any](obj T) http.HandlerFunc {
  586. return web.Wrap(func(ctx *context.APIContext) {
  587. theObj := new(T) // create a new form obj for every request but not use obj directly
  588. errs := binding.Bind(ctx.Req, theObj)
  589. if len(errs) > 0 {
  590. ctx.Error(http.StatusUnprocessableEntity, "validationError", fmt.Sprintf("%s: %s", errs[0].FieldNames, errs[0].Error()))
  591. return
  592. }
  593. web.SetForm(ctx, theObj)
  594. })
  595. }
  596. // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
  597. // in the session (if there is a user id stored in session other plugins might return the user
  598. // object for that id).
  599. //
  600. // The Session plugin is expected to be executed second, in order to skip authentication
  601. // for users that have already signed in.
  602. func buildAuthGroup() *auth.Group {
  603. group := auth.NewGroup(
  604. &auth.OAuth2{},
  605. &auth.HTTPSign{},
  606. &auth.Basic{}, // FIXME: this should be removed once we don't allow basic auth in API
  607. )
  608. specialAdd(group)
  609. return group
  610. }
  611. // Routes registers all v1 APIs routes to web application.
  612. func Routes(ctx gocontext.Context) *web.Route {
  613. m := web.NewRoute()
  614. m.Use(securityHeaders())
  615. if setting.CORSConfig.Enabled {
  616. m.Use(cors.Handler(cors.Options{
  617. // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option
  618. AllowedOrigins: setting.CORSConfig.AllowDomain,
  619. // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option
  620. AllowedMethods: setting.CORSConfig.Methods,
  621. AllowCredentials: setting.CORSConfig.AllowCredentials,
  622. AllowedHeaders: append([]string{"Authorization", "X-Gitea-OTP"}, setting.CORSConfig.Headers...),
  623. MaxAge: int(setting.CORSConfig.MaxAge.Seconds()),
  624. }))
  625. }
  626. m.Use(context.APIContexter())
  627. group := buildAuthGroup()
  628. if err := group.Init(ctx); err != nil {
  629. log.Error("Could not initialize '%s' auth method, error: %s", group.Name(), err)
  630. }
  631. // Get user from session if logged in.
  632. m.Use(auth.APIAuth(group))
  633. m.Use(context.ToggleAPI(&context.ToggleOptions{
  634. SignInRequired: setting.Service.RequireSignInView,
  635. }))
  636. m.Group("", func() {
  637. // Miscellaneous (no scope required)
  638. if setting.API.EnableSwagger {
  639. m.Get("/swagger", func(ctx *context.APIContext) {
  640. ctx.Redirect(setting.AppSubURL + "/api/swagger")
  641. })
  642. }
  643. m.Get("/version", misc.Version)
  644. if setting.Federation.Enabled {
  645. m.Get("/nodeinfo", misc.NodeInfo)
  646. m.Group("/activitypub", func() {
  647. // deprecated, remove in 1.20, use /user-id/{user-id} instead
  648. m.Group("/user/{username}", func() {
  649. m.Get("", activitypub.Person)
  650. m.Post("/inbox", activitypub.ReqHTTPSignature(), activitypub.PersonInbox)
  651. }, context_service.UserAssignmentAPI())
  652. m.Group("/user-id/{user-id}", func() {
  653. m.Get("", activitypub.Person)
  654. m.Post("/inbox", activitypub.ReqHTTPSignature(), activitypub.PersonInbox)
  655. }, context_service.UserIDAssignmentAPI())
  656. })
  657. }
  658. m.Get("/signing-key.gpg", misc.SigningKey)
  659. m.Post("/markup", bind(api.MarkupOption{}), misc.Markup)
  660. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  661. m.Post("/markdown/raw", misc.MarkdownRaw)
  662. m.Group("/settings", func() {
  663. m.Get("/ui", settings.GetGeneralUISettings)
  664. m.Get("/api", settings.GetGeneralAPISettings)
  665. m.Get("/attachment", settings.GetGeneralAttachmentSettings)
  666. m.Get("/repository", settings.GetGeneralRepoSettings)
  667. })
  668. // Notifications (requires 'notification' scope)
  669. m.Group("/notifications", func() {
  670. m.Combo("").
  671. Get(notify.ListNotifications).
  672. Put(notify.ReadNotifications)
  673. m.Get("/new", notify.NewAvailable)
  674. m.Combo("/threads/{id}").
  675. Get(notify.GetThread).
  676. Patch(notify.ReadThread)
  677. }, reqToken(auth_model.AccessTokenScopeNotification))
  678. // Users (no scope required)
  679. m.Group("/users", func() {
  680. m.Get("/search", reqExploreSignIn(), user.Search)
  681. m.Group("/{username}", func() {
  682. m.Get("", reqExploreSignIn(), user.GetInfo)
  683. if setting.Service.EnableUserHeatmap {
  684. m.Get("/heatmap", user.GetUserHeatmapData)
  685. }
  686. m.Get("/repos", reqExploreSignIn(), user.ListUserRepos)
  687. m.Group("/tokens", func() {
  688. m.Combo("").Get(user.ListAccessTokens).
  689. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  690. m.Combo("/{id}").Delete(user.DeleteAccessToken)
  691. }, reqBasicAuth())
  692. }, context_service.UserAssignmentAPI())
  693. })
  694. // (no scope required)
  695. m.Group("/users", func() {
  696. m.Group("/{username}", func() {
  697. m.Get("/keys", user.ListPublicKeys)
  698. m.Get("/gpg_keys", user.ListGPGKeys)
  699. m.Get("/followers", user.ListFollowers)
  700. m.Group("/following", func() {
  701. m.Get("", user.ListFollowing)
  702. m.Get("/{target}", user.CheckFollowing)
  703. })
  704. m.Get("/starred", user.GetStarredRepos)
  705. m.Get("/subscriptions", user.GetWatchedRepos)
  706. }, context_service.UserAssignmentAPI())
  707. }, reqToken(""))
  708. m.Group("/user", func() {
  709. m.Get("", user.GetAuthenticatedUser)
  710. m.Group("/settings", func() {
  711. m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings)
  712. m.Patch("", reqToken(auth_model.AccessTokenScopeUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings)
  713. })
  714. m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails).
  715. Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail).
  716. Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail)
  717. m.Get("/followers", user.ListMyFollowers)
  718. m.Group("/following", func() {
  719. m.Get("", user.ListMyFollowing)
  720. m.Group("/{username}", func() {
  721. m.Get("", user.CheckMyFollowing)
  722. m.Put("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Follow) // requires 'user:follow' scope
  723. m.Delete("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Unfollow) // requires 'user:follow' scope
  724. }, context_service.UserAssignmentAPI())
  725. })
  726. // (admin:public_key scope)
  727. m.Group("/keys", func() {
  728. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.ListMyPublicKeys).
  729. Post(reqToken(auth_model.AccessTokenScopeWritePublicKey), bind(api.CreateKeyOption{}), user.CreatePublicKey)
  730. m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.GetPublicKey).
  731. Delete(reqToken(auth_model.AccessTokenScopeWritePublicKey), user.DeletePublicKey)
  732. })
  733. // (admin:application scope)
  734. m.Group("/applications", func() {
  735. m.Combo("/oauth2").
  736. Get(reqToken(auth_model.AccessTokenScopeReadApplication), user.ListOauth2Applications).
  737. Post(reqToken(auth_model.AccessTokenScopeWriteApplication), bind(api.CreateOAuth2ApplicationOptions{}), user.CreateOauth2Application)
  738. m.Combo("/oauth2/{id}").
  739. Delete(reqToken(auth_model.AccessTokenScopeWriteApplication), user.DeleteOauth2Application).
  740. Patch(reqToken(auth_model.AccessTokenScopeWriteApplication), bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application).
  741. Get(reqToken(auth_model.AccessTokenScopeReadApplication), user.GetOauth2Application)
  742. })
  743. // (admin:gpg_key scope)
  744. m.Group("/gpg_keys", func() {
  745. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.ListMyGPGKeys).
  746. Post(reqToken(auth_model.AccessTokenScopeWriteGPGKey), bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  747. m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetGPGKey).
  748. Delete(reqToken(auth_model.AccessTokenScopeWriteGPGKey), user.DeleteGPGKey)
  749. })
  750. m.Get("/gpg_key_token", reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetVerificationToken)
  751. m.Post("/gpg_key_verify", reqToken(auth_model.AccessTokenScopeReadGPGKey), bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey)
  752. // (repo scope)
  753. m.Combo("/repos", reqToken(auth_model.AccessTokenScopeRepo)).Get(user.ListMyRepos).
  754. Post(bind(api.CreateRepoOption{}), repo.Create)
  755. // (repo scope)
  756. m.Group("/starred", func() {
  757. m.Get("", user.GetMyStarredRepos)
  758. m.Group("/{username}/{reponame}", func() {
  759. m.Get("", user.IsStarring)
  760. m.Put("", user.Star)
  761. m.Delete("", user.Unstar)
  762. }, repoAssignment())
  763. }, reqToken(auth_model.AccessTokenScopeRepo))
  764. m.Get("/times", reqToken(auth_model.AccessTokenScopeRepo), repo.ListMyTrackedTimes)
  765. m.Get("/stopwatches", reqToken(auth_model.AccessTokenScopeRepo), repo.GetStopwatches)
  766. m.Get("/subscriptions", reqToken(auth_model.AccessTokenScopeRepo), user.GetMyWatchedRepos)
  767. m.Get("/teams", reqToken(auth_model.AccessTokenScopeRepo), org.ListUserTeams)
  768. m.Group("/hooks", func() {
  769. m.Combo("").Get(user.ListHooks).
  770. Post(bind(api.CreateHookOption{}), user.CreateHook)
  771. m.Combo("/{id}").Get(user.GetHook).
  772. Patch(bind(api.EditHookOption{}), user.EditHook).
  773. Delete(user.DeleteHook)
  774. }, reqToken(auth_model.AccessTokenScopeAdminUserHook), reqWebhooksEnabled())
  775. }, reqToken(""))
  776. // Repositories
  777. m.Post("/org/{org}/repos", reqToken(auth_model.AccessTokenScopeAdminOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated)
  778. m.Combo("/repositories/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.GetByID)
  779. m.Group("/repos", func() {
  780. m.Get("/search", repo.Search)
  781. m.Get("/issues/search", repo.SearchIssues)
  782. // (repo scope)
  783. m.Post("/migrate", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MigrateRepoOptions{}), repo.Migrate)
  784. m.Group("/{username}/{reponame}", func() {
  785. m.Combo("").Get(reqAnyRepoReader(), repo.Get).
  786. Delete(reqToken(auth_model.AccessTokenScopeDeleteRepo), reqOwner(), repo.Delete).
  787. Patch(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit)
  788. m.Post("/generate", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate)
  789. m.Group("/transfer", func() {
  790. m.Post("", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer)
  791. m.Post("/accept", repo.AcceptTransfer)
  792. m.Post("/reject", repo.RejectTransfer)
  793. }, reqToken(auth_model.AccessTokenScopeRepo))
  794. m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)).
  795. Get(notify.ListRepoNotifications).
  796. Put(notify.ReadRepoNotifications)
  797. m.Group("/hooks/git", func() {
  798. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListGitHooks)
  799. m.Group("/{id}", func() {
  800. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetGitHook).
  801. Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditGitHookOption{}), repo.EditGitHook).
  802. Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteGitHook)
  803. })
  804. }, reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true))
  805. m.Group("/hooks", func() {
  806. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListHooks).
  807. Post(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.CreateHookOption{}), repo.CreateHook)
  808. m.Group("/{id}", func() {
  809. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetHook).
  810. Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditHookOption{}), repo.EditHook).
  811. Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteHook)
  812. m.Post("/tests", reqToken(auth_model.AccessTokenScopeReadRepoHook), context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook)
  813. })
  814. }, reqAdmin(), reqWebhooksEnabled())
  815. m.Group("/collaborators", func() {
  816. m.Get("", reqAnyRepoReader(), repo.ListCollaborators)
  817. m.Group("/{collaborator}", func() {
  818. m.Combo("").Get(reqAnyRepoReader(), repo.IsCollaborator).
  819. Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  820. Delete(reqAdmin(), repo.DeleteCollaborator)
  821. m.Get("/permission", repo.GetRepoPermissions)
  822. })
  823. }, reqToken(auth_model.AccessTokenScopeRepo))
  824. m.Get("/assignees", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetAssignees)
  825. m.Get("/reviewers", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetReviewers)
  826. m.Group("/teams", func() {
  827. m.Get("", reqAnyRepoReader(), repo.ListTeams)
  828. m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam).
  829. Put(reqAdmin(), repo.AddTeam).
  830. Delete(reqAdmin(), repo.DeleteTeam)
  831. }, reqToken(auth_model.AccessTokenScopeRepo))
  832. m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
  833. m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS)
  834. m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive)
  835. m.Combo("/forks").Get(repo.ListForks).
  836. Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
  837. m.Group("/branches", func() {
  838. m.Get("", repo.ListBranches)
  839. m.Get("/*", repo.GetBranch)
  840. m.Delete("/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.DeleteBranch)
  841. m.Post("", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch)
  842. }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode))
  843. m.Group("/branch_protections", func() {
  844. m.Get("", repo.ListBranchProtections)
  845. m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection)
  846. m.Group("/{name}", func() {
  847. m.Get("", repo.GetBranchProtection)
  848. m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection)
  849. m.Delete("", repo.DeleteBranchProtection)
  850. })
  851. }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin())
  852. m.Group("/tags", func() {
  853. m.Get("", repo.ListTags)
  854. m.Get("/*", repo.GetTag)
  855. m.Post("", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag)
  856. m.Delete("/*", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteTag)
  857. }, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true))
  858. m.Group("/keys", func() {
  859. m.Combo("").Get(repo.ListDeployKeys).
  860. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  861. m.Combo("/{id}").Get(repo.GetDeployKey).
  862. Delete(repo.DeleteDeploykey)
  863. }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin())
  864. m.Group("/times", func() {
  865. m.Combo("").Get(repo.ListTrackedTimesByRepository)
  866. m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser)
  867. }, mustEnableIssues, reqToken(auth_model.AccessTokenScopeRepo))
  868. m.Group("/wiki", func() {
  869. m.Combo("/page/{pageName}").
  870. Get(repo.GetWikiPage).
  871. Patch(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.EditWikiPage).
  872. Delete(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), repo.DeleteWikiPage)
  873. m.Get("/revisions/{pageName}", repo.ListPageRevisions)
  874. m.Post("/new", mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage)
  875. m.Get("/pages", repo.ListWikiPages)
  876. }, mustEnableWiki)
  877. m.Group("/issues", func() {
  878. m.Combo("").Get(repo.ListIssues).
  879. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue)
  880. m.Group("/comments", func() {
  881. m.Get("", repo.ListRepoIssueComments)
  882. m.Group("/{id}", func() {
  883. m.Combo("").
  884. Get(repo.GetIssueComment).
  885. Patch(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  886. Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueComment)
  887. m.Combo("/reactions").
  888. Get(repo.GetIssueCommentReactions).
  889. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction).
  890. Delete(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction)
  891. m.Group("/assets", func() {
  892. m.Combo("").
  893. Get(repo.ListIssueCommentAttachments).
  894. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.CreateIssueCommentAttachment)
  895. m.Combo("/{asset}").
  896. Get(repo.GetIssueCommentAttachment).
  897. Patch(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.EditAttachmentOptions{}), repo.EditIssueCommentAttachment).
  898. Delete(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.DeleteIssueCommentAttachment)
  899. }, mustEnableAttachments)
  900. })
  901. })
  902. m.Group("/{index}", func() {
  903. m.Combo("").Get(repo.GetIssue).
  904. Patch(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditIssueOption{}), repo.EditIssue).
  905. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), context.ReferencesGitRepo(), repo.DeleteIssue)
  906. m.Group("/comments", func() {
  907. m.Combo("").Get(repo.ListIssueComments).
  908. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  909. m.Combo("/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated).
  910. Delete(repo.DeleteIssueCommentDeprecated)
  911. })
  912. m.Get("/timeline", repo.ListIssueCommentsAndTimeline)
  913. m.Group("/labels", func() {
  914. m.Combo("").Get(repo.ListIssueLabels).
  915. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  916. Put(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  917. Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.ClearIssueLabels)
  918. m.Delete("/{id}", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueLabel)
  919. })
  920. m.Group("/times", func() {
  921. m.Combo("").
  922. Get(repo.ListTrackedTimes).
  923. Post(bind(api.AddTimeOption{}), repo.AddTime).
  924. Delete(repo.ResetIssueTime)
  925. m.Delete("/{id}", repo.DeleteTime)
  926. }, reqToken(auth_model.AccessTokenScopeRepo))
  927. m.Combo("/deadline").Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  928. m.Group("/stopwatch", func() {
  929. m.Post("/start", reqToken(auth_model.AccessTokenScopeRepo), repo.StartIssueStopwatch)
  930. m.Post("/stop", reqToken(auth_model.AccessTokenScopeRepo), repo.StopIssueStopwatch)
  931. m.Delete("/delete", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueStopwatch)
  932. })
  933. m.Group("/subscriptions", func() {
  934. m.Get("", repo.GetIssueSubscribers)
  935. m.Get("/check", reqToken(auth_model.AccessTokenScopeRepo), repo.CheckIssueSubscription)
  936. m.Put("/{user}", reqToken(auth_model.AccessTokenScopeRepo), repo.AddIssueSubscription)
  937. m.Delete("/{user}", reqToken(auth_model.AccessTokenScopeRepo), repo.DelIssueSubscription)
  938. })
  939. m.Combo("/reactions").
  940. Get(repo.GetIssueReactions).
  941. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.PostIssueReaction).
  942. Delete(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.DeleteIssueReaction)
  943. m.Group("/assets", func() {
  944. m.Combo("").
  945. Get(repo.ListIssueAttachments).
  946. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.CreateIssueAttachment)
  947. m.Combo("/{asset}").
  948. Get(repo.GetIssueAttachment).
  949. Patch(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.EditAttachmentOptions{}), repo.EditIssueAttachment).
  950. Delete(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.DeleteIssueAttachment)
  951. }, mustEnableAttachments)
  952. m.Combo("/dependencies").
  953. Get(repo.GetIssueDependencies).
  954. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.IssueMeta{}), repo.CreateIssueDependency).
  955. Delete(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.IssueMeta{}), repo.RemoveIssueDependency)
  956. m.Combo("/blocks").
  957. Get(repo.GetIssueBlocks).
  958. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueMeta{}), repo.CreateIssueBlocking).
  959. Delete(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueMeta{}), repo.RemoveIssueBlocking)
  960. })
  961. }, mustEnableIssuesOrPulls)
  962. m.Group("/labels", func() {
  963. m.Combo("").Get(repo.ListLabels).
  964. Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel)
  965. m.Combo("/{id}").Get(repo.GetLabel).
  966. Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel).
  967. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel)
  968. })
  969. m.Post("/markup", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MarkupOption{}), misc.Markup)
  970. m.Post("/markdown", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MarkdownOption{}), misc.Markdown)
  971. m.Post("/markdown/raw", reqToken(auth_model.AccessTokenScopeRepo), misc.MarkdownRaw)
  972. m.Group("/milestones", func() {
  973. m.Combo("").Get(repo.ListMilestones).
  974. Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  975. m.Combo("/{id}").Get(repo.GetMilestone).
  976. Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  977. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone)
  978. })
  979. m.Get("/stargazers", repo.ListStargazers)
  980. m.Get("/subscribers", repo.ListSubscribers)
  981. m.Group("/subscription", func() {
  982. m.Get("", user.IsWatching)
  983. m.Put("", reqToken(auth_model.AccessTokenScopeRepo), user.Watch)
  984. m.Delete("", reqToken(auth_model.AccessTokenScopeRepo), user.Unwatch)
  985. })
  986. m.Group("/releases", func() {
  987. m.Combo("").Get(repo.ListReleases).
  988. Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  989. m.Combo("/latest").Get(repo.GetLatestRelease)
  990. m.Group("/{id}", func() {
  991. m.Combo("").Get(repo.GetRelease).
  992. Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease).
  993. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease)
  994. m.Group("/assets", func() {
  995. m.Combo("").Get(repo.ListReleaseAttachments).
  996. Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment)
  997. m.Combo("/{asset}").Get(repo.GetReleaseAttachment).
  998. Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment).
  999. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment)
  1000. })
  1001. })
  1002. m.Group("/tags", func() {
  1003. m.Combo("/{tag}").
  1004. Get(repo.GetReleaseByTag).
  1005. Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag)
  1006. })
  1007. }, reqRepoReader(unit.TypeReleases))
  1008. m.Post("/mirror-sync", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.MirrorSync)
  1009. m.Post("/push_mirrors-sync", reqAdmin(), reqToken(auth_model.AccessTokenScopeRepo), repo.PushMirrorSync)
  1010. m.Group("/push_mirrors", func() {
  1011. m.Combo("").Get(repo.ListPushMirrors).
  1012. Post(bind(api.CreatePushMirrorOption{}), repo.AddPushMirror)
  1013. m.Combo("/{name}").
  1014. Delete(repo.DeletePushMirrorByRemoteName).
  1015. Get(repo.GetPushMirrorByName)
  1016. }, reqAdmin(), reqToken(auth_model.AccessTokenScopeRepo))
  1017. m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig)
  1018. m.Group("/pulls", func() {
  1019. m.Combo("").Get(repo.ListPullRequests).
  1020. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  1021. m.Group("/{index}", func() {
  1022. m.Combo("").Get(repo.GetPullRequest).
  1023. Patch(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  1024. m.Get(".{diffType:diff|patch}", repo.DownloadPullDiffOrPatch)
  1025. m.Post("/update", reqToken(auth_model.AccessTokenScopeRepo), repo.UpdatePullRequest)
  1026. m.Get("/commits", repo.GetPullRequestCommits)
  1027. m.Get("/files", repo.GetPullRequestFiles)
  1028. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  1029. Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest).
  1030. Delete(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.CancelScheduledAutoMerge)
  1031. m.Group("/reviews", func() {
  1032. m.Combo("").
  1033. Get(repo.ListPullReviews).
  1034. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview)
  1035. m.Group("/{id}", func() {
  1036. m.Combo("").
  1037. Get(repo.GetPullReview).
  1038. Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeletePullReview).
  1039. Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview)
  1040. m.Combo("/comments").
  1041. Get(repo.GetPullReviewComments)
  1042. m.Post("/dismissals", reqToken(auth_model.AccessTokenScopeRepo), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview)
  1043. m.Post("/undismissals", reqToken(auth_model.AccessTokenScopeRepo), repo.UnDismissPullReview)
  1044. })
  1045. })
  1046. m.Combo("/requested_reviewers", reqToken(auth_model.AccessTokenScopeRepo)).
  1047. Delete(bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests).
  1048. Post(bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests)
  1049. })
  1050. }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo())
  1051. m.Group("/statuses", func() {
  1052. m.Combo("/{sha}").Get(repo.GetCommitStatuses).
  1053. Post(reqToken(auth_model.AccessTokenScopeRepoStatus), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  1054. }, reqRepoReader(unit.TypeCode))
  1055. m.Group("/commits", func() {
  1056. m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits)
  1057. m.Group("/{ref}", func() {
  1058. m.Get("/status", repo.GetCombinedCommitStatusByRef)
  1059. m.Get("/statuses", repo.GetCommitStatusesByRef)
  1060. }, context.ReferencesGitRepo())
  1061. }, reqRepoReader(unit.TypeCode))
  1062. m.Group("/git", func() {
  1063. m.Group("/commits", func() {
  1064. m.Get("/{sha}", repo.GetSingleCommit)
  1065. m.Get("/{sha}.{diffType:diff|patch}", repo.DownloadCommitDiffOrPatch)
  1066. })
  1067. m.Get("/refs", repo.GetGitAllRefs)
  1068. m.Get("/refs/*", repo.GetGitRefs)
  1069. m.Get("/trees/{sha}", repo.GetTree)
  1070. m.Get("/blobs/{sha}", repo.GetBlob)
  1071. m.Get("/tags/{sha}", repo.GetAnnotatedTag)
  1072. m.Get("/notes/{sha}", repo.GetNote)
  1073. }, context.ReferencesGitRepo(true), reqRepoReader(unit.TypeCode))
  1074. m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(auth_model.AccessTokenScopeRepo), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch)
  1075. m.Group("/contents", func() {
  1076. m.Get("", repo.GetContentsList)
  1077. m.Get("/*", repo.GetContents)
  1078. m.Group("/*", func() {
  1079. m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile)
  1080. m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile)
  1081. m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile)
  1082. }, reqToken(auth_model.AccessTokenScopeRepo))
  1083. }, reqRepoReader(unit.TypeCode))
  1084. m.Get("/signing-key.gpg", misc.SigningKey)
  1085. m.Group("/topics", func() {
  1086. m.Combo("").Get(repo.ListTopics).
  1087. Put(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics)
  1088. m.Group("/{topic}", func() {
  1089. m.Combo("").Put(reqToken(auth_model.AccessTokenScopeRepo), repo.AddTopic).
  1090. Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteTopic)
  1091. }, reqAdmin())
  1092. }, reqAnyRepoReader())
  1093. m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates)
  1094. m.Get("/issue_config", context.ReferencesGitRepo(), repo.GetIssueConfig)
  1095. m.Get("/issue_config/validate", context.ReferencesGitRepo(), repo.ValidateIssueConfig)
  1096. m.Get("/languages", reqRepoReader(unit.TypeCode), repo.GetLanguages)
  1097. }, repoAssignment())
  1098. })
  1099. // NOTE: these are Gitea package management API - see packages.CommonRoutes and packages.DockerContainerRoutes for endpoints that implement package manager APIs
  1100. m.Group("/packages/{username}", func() {
  1101. m.Group("/{type}/{name}/{version}", func() {
  1102. m.Get("", reqToken(auth_model.AccessTokenScopeReadPackage), packages.GetPackage)
  1103. m.Delete("", reqToken(auth_model.AccessTokenScopeDeletePackage), reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage)
  1104. m.Get("/files", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackageFiles)
  1105. })
  1106. m.Get("/", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackages)
  1107. }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead))
  1108. // Organizations
  1109. m.Get("/user/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMyOrgs)
  1110. m.Group("/users/{username}/orgs", func() {
  1111. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListUserOrgs)
  1112. m.Get("/{org}/permissions", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetUserOrgsPermissions)
  1113. }, context_service.UserAssignmentAPI())
  1114. m.Post("/orgs", reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateOrgOption{}), org.Create)
  1115. m.Get("/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetAll)
  1116. m.Group("/orgs/{org}", func() {
  1117. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.Get).
  1118. Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit).
  1119. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.Delete)
  1120. m.Combo("/repos").Get(reqToken(auth_model.AccessTokenScopeReadOrg), user.ListOrgRepos).
  1121. Post(reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  1122. m.Group("/members", func() {
  1123. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMembers)
  1124. m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsMember).
  1125. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteMember)
  1126. })
  1127. m.Group("/public_members", func() {
  1128. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListPublicMembers)
  1129. m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsPublicMember).
  1130. Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.PublicizeMember).
  1131. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.ConcealMember)
  1132. })
  1133. m.Group("/teams", func() {
  1134. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListTeams)
  1135. m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam)
  1136. m.Get("/search", reqToken(auth_model.AccessTokenScopeReadOrg), org.SearchTeam)
  1137. }, reqOrgMembership())
  1138. m.Group("/labels", func() {
  1139. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListLabels)
  1140. m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel)
  1141. m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetLabel).
  1142. Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel).
  1143. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteLabel)
  1144. })
  1145. m.Group("/hooks", func() {
  1146. m.Combo("").Get(org.ListHooks).
  1147. Post(bind(api.CreateHookOption{}), org.CreateHook)
  1148. m.Combo("/{id}").Get(org.GetHook).
  1149. Patch(bind(api.EditHookOption{}), org.EditHook).
  1150. Delete(org.DeleteHook)
  1151. }, reqToken(auth_model.AccessTokenScopeAdminOrgHook), reqOrgOwnership(), reqWebhooksEnabled())
  1152. }, orgAssignment(true))
  1153. m.Group("/teams/{teamid}", func() {
  1154. m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeam).
  1155. Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  1156. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteTeam)
  1157. m.Group("/members", func() {
  1158. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMembers)
  1159. m.Combo("/{username}").
  1160. Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMember).
  1161. Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.AddTeamMember).
  1162. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.RemoveTeamMember)
  1163. })
  1164. m.Group("/repos", func() {
  1165. m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepos)
  1166. m.Combo("/{org}/{reponame}").
  1167. Put(reqToken(auth_model.AccessTokenScopeWriteOrg), org.AddTeamRepository).
  1168. Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), org.RemoveTeamRepository).
  1169. Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepo)
  1170. })
  1171. }, orgAssignment(false, true), reqToken(""), reqTeamMembership())
  1172. m.Group("/admin", func() {
  1173. m.Group("/cron", func() {
  1174. m.Get("", admin.ListCronTasks)
  1175. m.Post("/{task}", admin.PostCronTask)
  1176. })
  1177. m.Get("/orgs", admin.GetAllOrgs)
  1178. m.Group("/users", func() {
  1179. m.Get("", admin.SearchUsers)
  1180. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  1181. m.Group("/{username}", func() {
  1182. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  1183. Delete(admin.DeleteUser)
  1184. m.Group("/keys", func() {
  1185. m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  1186. m.Delete("/{id}", admin.DeleteUserPublicKey)
  1187. })
  1188. m.Get("/orgs", org.ListUserOrgs)
  1189. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  1190. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  1191. m.Post("/rename", bind(api.RenameUserOption{}), admin.RenameUser)
  1192. }, context_service.UserAssignmentAPI())
  1193. })
  1194. m.Group("/emails", func() {
  1195. m.Get("", admin.GetAllEmails)
  1196. m.Get("/search", admin.SearchEmail)
  1197. })
  1198. m.Group("/unadopted", func() {
  1199. m.Get("", admin.ListUnadoptedRepositories)
  1200. m.Post("/{username}/{reponame}", admin.AdoptRepository)
  1201. m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository)
  1202. })
  1203. m.Group("/hooks", func() {
  1204. m.Combo("").Get(admin.ListHooks).
  1205. Post(bind(api.CreateHookOption{}), admin.CreateHook)
  1206. m.Combo("/{id}").Get(admin.GetHook).
  1207. Patch(bind(api.EditHookOption{}), admin.EditHook).
  1208. Delete(admin.DeleteHook)
  1209. })
  1210. }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin())
  1211. m.Group("/topics", func() {
  1212. m.Get("/search", repo.TopicSearch)
  1213. })
  1214. }, sudo())
  1215. return m
  1216. }
  1217. func securityHeaders() func(http.Handler) http.Handler {
  1218. return func(next http.Handler) http.Handler {
  1219. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  1220. // CORB: https://www.chromium.org/Home/chromium-security/corb-for-developers
  1221. // http://stackoverflow.com/a/3146618/244009
  1222. resp.Header().Set("x-content-type-options", "nosniff")
  1223. next.ServeHTTP(resp, req)
  1224. })
  1225. }
  1226. }