repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "net/http"
  7. "path"
  8. api "github.com/gogs/go-gogs-client"
  9. "github.com/pkg/errors"
  10. log "unknwon.dev/clog/v2"
  11. "gogs.io/gogs/internal/conf"
  12. "gogs.io/gogs/internal/context"
  13. "gogs.io/gogs/internal/db"
  14. "gogs.io/gogs/internal/form"
  15. "gogs.io/gogs/internal/route/api/v1/convert"
  16. )
  17. func Search(c *context.APIContext) {
  18. opts := &db.SearchRepoOptions{
  19. Keyword: path.Base(c.Query("q")),
  20. OwnerID: c.QueryInt64("uid"),
  21. PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")),
  22. Page: c.QueryInt("page"),
  23. }
  24. // Check visibility.
  25. if c.IsLogged && opts.OwnerID > 0 {
  26. if c.User.ID == opts.OwnerID {
  27. opts.Private = true
  28. } else {
  29. u, err := db.GetUserByID(opts.OwnerID)
  30. if err != nil {
  31. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  32. "ok": false,
  33. "error": err.Error(),
  34. })
  35. return
  36. }
  37. if u.IsOrganization() && u.IsOwnedBy(c.User.ID) {
  38. opts.Private = true
  39. }
  40. // FIXME: how about collaborators?
  41. }
  42. }
  43. repos, count, err := db.SearchRepositoryByName(opts)
  44. if err != nil {
  45. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  46. "ok": false,
  47. "error": err.Error(),
  48. })
  49. return
  50. }
  51. if err = db.RepositoryList(repos).LoadAttributes(); err != nil {
  52. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  53. "ok": false,
  54. "error": err.Error(),
  55. })
  56. return
  57. }
  58. results := make([]*api.Repository, len(repos))
  59. for i := range repos {
  60. results[i] = repos[i].APIFormatLegacy(nil)
  61. }
  62. c.SetLinkHeader(int(count), opts.PageSize)
  63. c.JSONSuccess(map[string]interface{}{
  64. "ok": true,
  65. "data": results,
  66. })
  67. }
  68. func listUserRepositories(c *context.APIContext, username string) {
  69. user, err := db.GetUserByName(username)
  70. if err != nil {
  71. c.NotFoundOrError(err, "get user by name")
  72. return
  73. }
  74. // Only list public repositories if user requests someone else's repository list,
  75. // or an organization isn't a member of.
  76. var ownRepos []*db.Repository
  77. if user.IsOrganization() {
  78. ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos)
  79. } else {
  80. ownRepos, err = db.GetUserRepositories(&db.UserRepoOptions{
  81. UserID: user.ID,
  82. Private: c.User.ID == user.ID,
  83. Page: 1,
  84. PageSize: user.NumRepos,
  85. })
  86. }
  87. if err != nil {
  88. c.Error(err, "get user repositories")
  89. return
  90. }
  91. if err = db.RepositoryList(ownRepos).LoadAttributes(); err != nil {
  92. c.Error(err, "load attributes")
  93. return
  94. }
  95. // Early return for querying other user's repositories
  96. if c.User.ID != user.ID {
  97. repos := make([]*api.Repository, len(ownRepos))
  98. for i := range ownRepos {
  99. repos[i] = ownRepos[i].APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true})
  100. }
  101. c.JSONSuccess(&repos)
  102. return
  103. }
  104. accessibleRepos, err := user.GetRepositoryAccesses()
  105. if err != nil {
  106. c.Error(err, "get repositories accesses")
  107. return
  108. }
  109. numOwnRepos := len(ownRepos)
  110. repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos))
  111. for i := range ownRepos {
  112. repos[i] = ownRepos[i].APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true})
  113. }
  114. i := numOwnRepos
  115. for repo, access := range accessibleRepos {
  116. repos[i] = repo.APIFormatLegacy(&api.Permission{
  117. Admin: access >= db.AccessModeAdmin,
  118. Push: access >= db.AccessModeWrite,
  119. Pull: true,
  120. })
  121. i++
  122. }
  123. c.JSONSuccess(&repos)
  124. }
  125. func ListMyRepos(c *context.APIContext) {
  126. listUserRepositories(c, c.User.Name)
  127. }
  128. func ListUserRepositories(c *context.APIContext) {
  129. listUserRepositories(c, c.Params(":username"))
  130. }
  131. func ListOrgRepositories(c *context.APIContext) {
  132. listUserRepositories(c, c.Params(":org"))
  133. }
  134. func CreateUserRepo(c *context.APIContext, owner *db.User, opt api.CreateRepoOption) {
  135. repo, err := db.CreateRepository(c.User, owner, db.CreateRepoOptionsLegacy{
  136. Name: opt.Name,
  137. Description: opt.Description,
  138. Gitignores: opt.Gitignores,
  139. License: opt.License,
  140. Readme: opt.Readme,
  141. IsPrivate: opt.Private,
  142. AutoInit: opt.AutoInit,
  143. })
  144. if err != nil {
  145. if db.IsErrRepoAlreadyExist(err) ||
  146. db.IsErrNameNotAllowed(err) {
  147. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  148. } else {
  149. if repo != nil {
  150. if err = db.DeleteRepository(c.User.ID, repo.ID); err != nil {
  151. log.Error("Failed to delete repository: %v", err)
  152. }
  153. }
  154. c.Error(err, "create repository")
  155. }
  156. return
  157. }
  158. c.JSON(201, repo.APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true}))
  159. }
  160. func Create(c *context.APIContext, opt api.CreateRepoOption) {
  161. // Shouldn't reach this condition, but just in case.
  162. if c.User.IsOrganization() {
  163. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Not allowed to create repository for organization."))
  164. return
  165. }
  166. CreateUserRepo(c, c.User, opt)
  167. }
  168. func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
  169. org, err := db.GetOrgByName(c.Params(":org"))
  170. if err != nil {
  171. c.NotFoundOrError(err, "get organization by name")
  172. return
  173. }
  174. if !org.IsOwnedBy(c.User.ID) {
  175. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  176. return
  177. }
  178. CreateUserRepo(c, org, opt)
  179. }
  180. func Migrate(c *context.APIContext, f form.MigrateRepo) {
  181. ctxUser := c.User
  182. // Not equal means context user is an organization,
  183. // or is another user/organization if current user is admin.
  184. if f.Uid != ctxUser.ID {
  185. org, err := db.GetUserByID(f.Uid)
  186. if err != nil {
  187. if db.IsErrUserNotExist(err) {
  188. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  189. } else {
  190. c.Error(err, "get user by ID")
  191. }
  192. return
  193. } else if !org.IsOrganization() && !c.User.IsAdmin {
  194. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not an organization."))
  195. return
  196. }
  197. ctxUser = org
  198. }
  199. if c.HasError() {
  200. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New(c.GetErrMsg()))
  201. return
  202. }
  203. if ctxUser.IsOrganization() && !c.User.IsAdmin {
  204. // Check ownership of organization.
  205. if !ctxUser.IsOwnedBy(c.User.ID) {
  206. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  207. return
  208. }
  209. }
  210. remoteAddr, err := f.ParseRemoteAddr(c.User)
  211. if err != nil {
  212. if db.IsErrInvalidCloneAddr(err) {
  213. addrErr := err.(db.ErrInvalidCloneAddr)
  214. switch {
  215. case addrErr.IsURLError:
  216. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  217. case addrErr.IsPermissionDenied:
  218. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("You are not allowed to import local repositories."))
  219. case addrErr.IsInvalidPath:
  220. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid local path, it does not exist or not a directory."))
  221. case addrErr.IsBlockedLocalAddress:
  222. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Clone address resolved to a local network address that is implicitly blocked."))
  223. default:
  224. c.Error(err, "unexpected error")
  225. }
  226. } else {
  227. c.Error(err, "parse remote address")
  228. }
  229. return
  230. }
  231. repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{
  232. Name: f.RepoName,
  233. Description: f.Description,
  234. IsPrivate: f.Private || conf.Repository.ForcePrivate,
  235. IsMirror: f.Mirror,
  236. RemoteAddr: remoteAddr,
  237. })
  238. if err != nil {
  239. if repo != nil {
  240. if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  241. log.Error("DeleteRepository: %v", errDelete)
  242. }
  243. }
  244. if db.IsErrReachLimitOfRepo(err) {
  245. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  246. } else {
  247. c.Error(errors.New(db.HandleMirrorCredentials(err.Error(), true)), "migrate repository")
  248. }
  249. return
  250. }
  251. log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
  252. c.JSON(201, repo.APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true}))
  253. }
  254. // FIXME: inject in the handler chain
  255. func parseOwnerAndRepo(c *context.APIContext) (*db.User, *db.Repository) {
  256. owner, err := db.GetUserByName(c.Params(":username"))
  257. if err != nil {
  258. if db.IsErrUserNotExist(err) {
  259. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  260. } else {
  261. c.Error(err, "get user by name")
  262. }
  263. return nil, nil
  264. }
  265. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  266. if err != nil {
  267. c.NotFoundOrError(err, "get repository by name")
  268. return nil, nil
  269. }
  270. return owner, repo
  271. }
  272. func Get(c *context.APIContext) {
  273. _, repo := parseOwnerAndRepo(c)
  274. if c.Written() {
  275. return
  276. }
  277. c.JSONSuccess(repo.APIFormatLegacy(&api.Permission{
  278. Admin: c.Repo.IsAdmin(),
  279. Push: c.Repo.IsWriter(),
  280. Pull: true,
  281. }))
  282. }
  283. func Delete(c *context.APIContext) {
  284. owner, repo := parseOwnerAndRepo(c)
  285. if c.Written() {
  286. return
  287. }
  288. if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
  289. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  290. return
  291. }
  292. if err := db.DeleteRepository(owner.ID, repo.ID); err != nil {
  293. c.Error(err, "delete repository")
  294. return
  295. }
  296. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  297. c.NoContent()
  298. }
  299. func ListForks(c *context.APIContext) {
  300. forks, err := c.Repo.Repository.GetForks()
  301. if err != nil {
  302. c.Error(err, "get forks")
  303. return
  304. }
  305. apiForks := make([]*api.Repository, len(forks))
  306. for i := range forks {
  307. if err := forks[i].GetOwner(); err != nil {
  308. c.Error(err, "get owner")
  309. return
  310. }
  311. apiForks[i] = forks[i].APIFormatLegacy(&api.Permission{
  312. Admin: c.User.IsAdminOfRepo(forks[i]),
  313. Push: c.User.IsWriterOfRepo(forks[i]),
  314. Pull: true,
  315. })
  316. }
  317. c.JSONSuccess(&apiForks)
  318. }
  319. func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
  320. _, repo := parseOwnerAndRepo(c)
  321. if c.Written() {
  322. return
  323. }
  324. if form.EnableIssues != nil {
  325. repo.EnableIssues = *form.EnableIssues
  326. }
  327. if form.EnableExternalTracker != nil {
  328. repo.EnableExternalTracker = *form.EnableExternalTracker
  329. }
  330. if form.ExternalTrackerURL != nil {
  331. repo.ExternalTrackerURL = *form.ExternalTrackerURL
  332. }
  333. if form.TrackerURLFormat != nil {
  334. repo.ExternalTrackerFormat = *form.TrackerURLFormat
  335. }
  336. if form.TrackerIssueStyle != nil {
  337. repo.ExternalTrackerStyle = *form.TrackerIssueStyle
  338. }
  339. if err := db.UpdateRepository(repo, false); err != nil {
  340. c.Error(err, "update repository")
  341. return
  342. }
  343. c.NoContent()
  344. }
  345. func Wiki(c *context.APIContext, form api.EditWikiOption) {
  346. _, repo := parseOwnerAndRepo(c)
  347. if c.Written() {
  348. return
  349. }
  350. if form.AllowPublicWiki != nil {
  351. repo.AllowPublicWiki = *form.AllowPublicWiki
  352. }
  353. if form.EnableExternalWiki != nil {
  354. repo.EnableExternalWiki = *form.EnableExternalWiki
  355. }
  356. if form.EnableWiki != nil {
  357. repo.EnableWiki = *form.EnableWiki
  358. }
  359. if form.ExternalWikiURL != nil {
  360. repo.ExternalWikiURL = *form.ExternalWikiURL
  361. }
  362. if err := db.UpdateRepository(repo, false); err != nil {
  363. c.Error(err, "update repository")
  364. return
  365. }
  366. c.NoContent()
  367. }
  368. func MirrorSync(c *context.APIContext) {
  369. _, repo := parseOwnerAndRepo(c)
  370. if c.Written() {
  371. return
  372. } else if !repo.IsMirror {
  373. c.NotFound()
  374. return
  375. }
  376. go db.MirrorQueue.Add(repo.ID)
  377. c.Status(http.StatusAccepted)
  378. }
  379. func Releases(c *context.APIContext) {
  380. _, repo := parseOwnerAndRepo(c)
  381. releases, err := db.GetReleasesByRepoID(repo.ID)
  382. if err != nil {
  383. c.Error(err, "get releases by repository ID")
  384. return
  385. }
  386. apiReleases := make([]*api.Release, 0, len(releases))
  387. for _, r := range releases {
  388. publisher, err := db.GetUserByID(r.PublisherID)
  389. if err != nil {
  390. c.Error(err, "get release publisher")
  391. return
  392. }
  393. r.Publisher = publisher
  394. }
  395. for _, r := range releases {
  396. apiReleases = append(apiReleases, r.APIFormat())
  397. }
  398. c.JSONSuccess(&apiReleases)
  399. }