api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package v1
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/go-macaron/binding"
  6. "gopkg.in/macaron.v1"
  7. "gogs.io/gogs/internal/context"
  8. "gogs.io/gogs/internal/database"
  9. "gogs.io/gogs/internal/form"
  10. )
  11. // repoAssignment extracts information from URL parameters to retrieve the repository,
  12. // and makes sure the context user has at least the read access to the repository.
  13. func repoAssignment() macaron.Handler {
  14. return func(c *context.APIContext) {
  15. username := c.Params(":username")
  16. reponame := c.Params(":reponame")
  17. var err error
  18. var owner *database.User
  19. // Check if the context user is the repository owner.
  20. if c.IsLogged && c.User.LowerName == strings.ToLower(username) {
  21. owner = c.User
  22. } else {
  23. owner, err = database.Handle.Users().GetByUsername(c.Req.Context(), username)
  24. if err != nil {
  25. c.NotFoundOrError(err, "get user by name")
  26. return
  27. }
  28. }
  29. c.Repo.Owner = owner
  30. repo, err := database.Handle.Repositories().GetByName(c.Req.Context(), owner.ID, reponame)
  31. if err != nil {
  32. c.NotFoundOrError(err, "get repository by name")
  33. return
  34. } else if err = repo.GetOwner(); err != nil {
  35. c.Error(err, "get owner")
  36. return
  37. }
  38. if c.IsTokenAuth && c.User.IsAdmin {
  39. c.Repo.AccessMode = database.AccessModeOwner
  40. } else {
  41. c.Repo.AccessMode = database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.ID,
  42. database.AccessModeOptions{
  43. OwnerID: repo.OwnerID,
  44. Private: repo.IsPrivate,
  45. },
  46. )
  47. }
  48. if !c.Repo.HasAccess() {
  49. c.NotFound()
  50. return
  51. }
  52. c.Repo.Repository = repo
  53. }
  54. }
  55. // orgAssignment extracts information from URL parameters to retrieve the organization or team.
  56. func orgAssignment(args ...bool) macaron.Handler {
  57. var (
  58. assignOrg bool
  59. assignTeam bool
  60. )
  61. if len(args) > 0 {
  62. assignOrg = args[0]
  63. }
  64. if len(args) > 1 {
  65. assignTeam = args[1]
  66. }
  67. return func(c *context.APIContext) {
  68. c.Org = new(context.APIOrganization)
  69. var err error
  70. if assignOrg {
  71. c.Org.Organization, err = database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":orgname"))
  72. if err != nil {
  73. c.NotFoundOrError(err, "get organization by name")
  74. return
  75. }
  76. }
  77. if assignTeam {
  78. c.Org.Team, err = database.GetTeamByID(c.ParamsInt64(":teamid"))
  79. if err != nil {
  80. c.NotFoundOrError(err, "get team by ID")
  81. return
  82. }
  83. }
  84. }
  85. }
  86. // reqToken makes sure the context user is authorized via access token.
  87. func reqToken() macaron.Handler {
  88. return func(c *context.Context) {
  89. if !c.IsTokenAuth {
  90. c.Status(http.StatusUnauthorized)
  91. return
  92. }
  93. }
  94. }
  95. // reqBasicAuth makes sure the context user is authorized via HTTP Basic Auth.
  96. func reqBasicAuth() macaron.Handler {
  97. return func(c *context.Context) {
  98. if !c.IsBasicAuth {
  99. c.Status(http.StatusUnauthorized)
  100. return
  101. }
  102. }
  103. }
  104. // reqAdmin makes sure the context user is a site admin.
  105. func reqAdmin() macaron.Handler {
  106. return func(c *context.Context) {
  107. if !c.IsLogged || !c.User.IsAdmin {
  108. c.Status(http.StatusForbidden)
  109. return
  110. }
  111. }
  112. }
  113. // reqRepoWriter makes sure the context user has at least write access to the repository.
  114. func reqRepoWriter() macaron.Handler {
  115. return func(c *context.Context) {
  116. if !c.Repo.IsWriter() {
  117. c.Status(http.StatusForbidden)
  118. return
  119. }
  120. }
  121. }
  122. // reqRepoAdmin makes sure the context user has at least admin access to the repository.
  123. func reqRepoAdmin() macaron.Handler {
  124. return func(c *context.Context) {
  125. if !c.Repo.IsAdmin() {
  126. c.Status(http.StatusForbidden)
  127. return
  128. }
  129. }
  130. }
  131. // reqRepoOwner makes sure the context user has owner access to the repository.
  132. func reqRepoOwner() macaron.Handler {
  133. return func(c *context.Context) {
  134. if !c.Repo.IsOwner() {
  135. c.Status(http.StatusForbidden)
  136. return
  137. }
  138. }
  139. }
  140. func mustEnableIssues(c *context.APIContext) {
  141. if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker {
  142. c.NotFound()
  143. return
  144. }
  145. }
  146. // RegisterRoutes registers all route in API v1 to the web application.
  147. // FIXME: custom form error response
  148. func RegisterRoutes(m *macaron.Macaron) {
  149. bind := binding.Bind
  150. m.Group("/v1", func() {
  151. // Handle preflight OPTIONS request
  152. m.Options("/*", func() {})
  153. // Miscellaneous
  154. m.Post("/markdown", bind(markdownRequest{}), markdown)
  155. m.Post("/markdown/raw", markdownRaw)
  156. // Users
  157. m.Group("/users", func() {
  158. m.Get("/search", searchUsers)
  159. m.Group("/:username", func() {
  160. m.Get("", getUserProfile)
  161. m.Group("/tokens", func() {
  162. accessTokensHandler := newAccessTokensHandler(newAccessTokensStore())
  163. m.Combo("").
  164. Get(accessTokensHandler.List()).
  165. Post(bind(createAccessTokenRequest{}), accessTokensHandler.Create())
  166. }, reqBasicAuth())
  167. })
  168. })
  169. m.Group("/users", func() {
  170. m.Group("/:username", func() {
  171. m.Get("/keys", listPublicKeys)
  172. m.Get("/followers", listFollowers)
  173. m.Group("/following", func() {
  174. m.Get("", listFollowing)
  175. m.Get("/:target", checkFollowing)
  176. })
  177. })
  178. }, reqToken())
  179. m.Group("/user", func() {
  180. m.Get("", getAuthenticatedUser)
  181. m.Combo("/emails").
  182. Get(listEmails).
  183. Post(bind(createEmailRequest{}), addEmail).
  184. Delete(bind(createEmailRequest{}), deleteEmail)
  185. m.Get("/followers", listMyFollowers)
  186. m.Group("/following", func() {
  187. m.Get("", listMyFollowing)
  188. m.Combo("/:username").
  189. Get(checkMyFollowing).
  190. Put(follow).
  191. Delete(unfollow)
  192. })
  193. m.Group("/keys", func() {
  194. m.Combo("").
  195. Get(listMyPublicKeys).
  196. Post(bind(createPublicKeyRequest{}), createPublicKey)
  197. m.Combo("/:id").
  198. Get(getPublicKey).
  199. Delete(deletePublicKey)
  200. })
  201. m.Get("/issues", listUserIssues)
  202. }, reqToken())
  203. // Repositories
  204. m.Get("/users/:username/repos", reqToken(), listUserRepositories)
  205. m.Get("/orgs/:org/repos", reqToken(), listOrgRepositories)
  206. m.Combo("/user/repos", reqToken()).
  207. Get(listMyRepos).
  208. Post(bind(createRepoRequest{}), createRepo)
  209. m.Post("/org/:org/repos", reqToken(), bind(createRepoRequest{}), createOrgRepo)
  210. m.Group("/repos", func() {
  211. m.Get("/search", searchRepos)
  212. m.Get("/:username/:reponame", repoAssignment(), getRepo)
  213. m.Get("/:username/:reponame/releases", repoAssignment(), releases)
  214. })
  215. m.Group("/repos", func() {
  216. m.Post("/migrate", bind(form.MigrateRepo{}), migrate)
  217. m.Delete("/:username/:reponame", repoAssignment(), reqRepoOwner(), deleteRepo)
  218. m.Group("/:username/:reponame", func() {
  219. m.Group("/hooks", func() {
  220. m.Combo("").
  221. Get(listHooks).
  222. Post(bind(createHookRequest{}), createHook)
  223. m.Combo("/:id").
  224. Patch(bind(editHookRequest{}), editHook).
  225. Delete(deleteHook)
  226. }, reqRepoAdmin())
  227. m.Group("/collaborators", func() {
  228. m.Get("", listCollaborators)
  229. m.Combo("/:collaborator").
  230. Get(isCollaborator).
  231. Put(bind(addCollaboratorRequest{}), addCollaborator).
  232. Delete(deleteCollaborator)
  233. }, reqRepoAdmin())
  234. m.Get("/raw/*", context.RepoRef(), getRawFile)
  235. m.Group("/contents", func() {
  236. m.Get("", getContents)
  237. m.Combo("/*").
  238. Get(getContents).
  239. Put(reqRepoWriter(), bind(putContentsRequest{}), putContents)
  240. })
  241. m.Get("/archive/*", getArchive)
  242. m.Group("/git", func() {
  243. m.Group("/trees", func() {
  244. m.Get("/:sha", getRepoGitTree)
  245. })
  246. m.Group("/blobs", func() {
  247. m.Get("/:sha", repoGitBlob)
  248. })
  249. })
  250. m.Get("/forks", listForks)
  251. m.Get("/tags", listTags)
  252. m.Group("/branches", func() {
  253. m.Get("", listBranches)
  254. m.Get("/*", getBranch)
  255. })
  256. m.Group("/commits", func() {
  257. m.Get("/:sha", getSingleCommit)
  258. m.Get("", getAllCommits)
  259. m.Get("/*", getReferenceSHA)
  260. })
  261. m.Group("/keys", func() {
  262. m.Combo("").
  263. Get(listDeployKeys).
  264. Post(bind(createDeployKeyRequest{}), createDeployKey)
  265. m.Combo("/:id").
  266. Get(getDeployKey).
  267. Delete(deleteDeploykey)
  268. }, reqRepoAdmin())
  269. m.Group("/issues", func() {
  270. m.Combo("").
  271. Get(listIssues).
  272. Post(bind(createIssueRequest{}), createIssue)
  273. m.Group("/comments", func() {
  274. m.Get("", listRepoIssueComments)
  275. m.Patch("/:id", bind(editIssueCommentRequest{}), editIssueComment)
  276. })
  277. m.Group("/:index", func() {
  278. m.Combo("").
  279. Get(getIssue).
  280. Patch(bind(editIssueRequest{}), editIssue)
  281. m.Group("/comments", func() {
  282. m.Combo("").
  283. Get(listIssueComments).
  284. Post(bind(createIssueCommentRequest{}), createIssueComment)
  285. m.Combo("/:id").
  286. Patch(bind(editIssueCommentRequest{}), editIssueComment).
  287. Delete(deleteIssueComment)
  288. })
  289. m.Get("/labels", listIssueLabels)
  290. m.Group("/labels", func() {
  291. m.Combo("").
  292. Post(bind(issueLabelsRequest{}), addIssueLabels).
  293. Put(bind(issueLabelsRequest{}), replaceIssueLabels).
  294. Delete(clearIssueLabels)
  295. m.Delete("/:id", deleteIssueLabel)
  296. }, reqRepoWriter())
  297. })
  298. }, mustEnableIssues)
  299. m.Group("/labels", func() {
  300. m.Get("", listLabels)
  301. m.Get("/:id", getLabel)
  302. })
  303. m.Group("/labels", func() {
  304. m.Post("", bind(createLabelRequest{}), createLabel)
  305. m.Combo("/:id").
  306. Patch(bind(editLabelRequest{}), editLabel).
  307. Delete(deleteLabel)
  308. }, reqRepoWriter())
  309. m.Group("/milestones", func() {
  310. m.Get("", listMilestones)
  311. m.Get("/:id", getMilestone)
  312. })
  313. m.Group("/milestones", func() {
  314. m.Post("", bind(createMilestoneRequest{}), createMilestone)
  315. m.Combo("/:id").
  316. Patch(bind(editMilestoneRequest{}), editMilestone).
  317. Delete(deleteMilestone)
  318. }, reqRepoWriter())
  319. m.Patch("/issue-tracker", reqRepoWriter(), bind(editIssueTrackerRequest{}), issueTracker)
  320. m.Patch("/wiki", reqRepoWriter(), bind(editWikiRequest{}), wiki)
  321. m.Post("/mirror-sync", reqRepoWriter(), mirrorSync)
  322. m.Get("/editorconfig/:filename", context.RepoRef(), getEditorconfig)
  323. }, repoAssignment())
  324. }, reqToken())
  325. m.Get("/issues", reqToken(), listUserIssues)
  326. // Organizations
  327. m.Combo("/user/orgs", reqToken()).
  328. Get(listMyOrgs).
  329. Post(bind(createOrgRequest{}), createMyOrg)
  330. m.Get("/users/:username/orgs", listUserOrgs)
  331. m.Group("/orgs/:orgname", func() {
  332. m.Combo("").
  333. Get(getOrg).
  334. Patch(bind(editOrgRequest{}), editOrg)
  335. m.Get("/teams", listTeams)
  336. }, orgAssignment(true))
  337. m.Group("/admin", func() {
  338. m.Group("/users", func() {
  339. m.Post("", bind(adminCreateUserRequest{}), adminCreateUser)
  340. m.Group("/:username", func() {
  341. m.Combo("").
  342. Patch(bind(adminEditUserRequest{}), adminEditUser).
  343. Delete(adminDeleteUser)
  344. m.Post("/keys", bind(createPublicKeyRequest{}), adminCreatePublicKey)
  345. m.Post("/orgs", bind(createOrgRequest{}), adminCreateOrg)
  346. m.Post("/repos", bind(createRepoRequest{}), adminCreateRepo)
  347. })
  348. })
  349. m.Group("/orgs/:orgname", func() {
  350. m.Group("/teams", func() {
  351. m.Post("", orgAssignment(true), bind(adminCreateTeamRequest{}), adminCreateTeam)
  352. })
  353. })
  354. m.Group("/teams", func() {
  355. m.Group("/:teamid", func() {
  356. m.Get("/members", adminListTeamMembers)
  357. m.Combo("/members/:username").
  358. Put(adminAddTeamMember).
  359. Delete(adminRemoveTeamMember)
  360. m.Combo("/repos/:reponame").
  361. Put(adminAddTeamRepository).
  362. Delete(adminRemoveTeamRepository)
  363. }, orgAssignment(false, true))
  364. })
  365. }, reqAdmin())
  366. m.Any("/*", func(c *context.Context) {
  367. c.NotFound()
  368. })
  369. }, context.APIContexter())
  370. }