repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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].APIFormat(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].APIFormat(&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].APIFormat(&api.Permission{Admin: true, Push: true, Pull: true})
  113. }
  114. i := numOwnRepos
  115. for repo, access := range accessibleRepos {
  116. repos[i] = repo.APIFormat(&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.CreateRepoOptions{
  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.APIFormat(&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. default:
  222. c.Error(err, "unexpected error")
  223. }
  224. } else {
  225. c.Error(err, "parse remote address")
  226. }
  227. return
  228. }
  229. repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{
  230. Name: f.RepoName,
  231. Description: f.Description,
  232. IsPrivate: f.Private || conf.Repository.ForcePrivate,
  233. IsMirror: f.Mirror,
  234. RemoteAddr: remoteAddr,
  235. })
  236. if err != nil {
  237. if repo != nil {
  238. if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  239. log.Error("DeleteRepository: %v", errDelete)
  240. }
  241. }
  242. if db.IsErrReachLimitOfRepo(err) {
  243. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  244. } else {
  245. c.Error(errors.New(db.HandleMirrorCredentials(err.Error(), true)), "migrate repository")
  246. }
  247. return
  248. }
  249. log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
  250. c.JSON(201, repo.APIFormat(&api.Permission{Admin: true, Push: true, Pull: true}))
  251. }
  252. // FIXME: inject in the handler chain
  253. func parseOwnerAndRepo(c *context.APIContext) (*db.User, *db.Repository) {
  254. owner, err := db.GetUserByName(c.Params(":username"))
  255. if err != nil {
  256. if db.IsErrUserNotExist(err) {
  257. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  258. } else {
  259. c.Error(err, "get user by name")
  260. }
  261. return nil, nil
  262. }
  263. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  264. if err != nil {
  265. c.NotFoundOrError(err, "get repository by name")
  266. return nil, nil
  267. }
  268. return owner, repo
  269. }
  270. func Get(c *context.APIContext) {
  271. _, repo := parseOwnerAndRepo(c)
  272. if c.Written() {
  273. return
  274. }
  275. c.JSONSuccess(repo.APIFormat(&api.Permission{
  276. Admin: c.Repo.IsAdmin(),
  277. Push: c.Repo.IsWriter(),
  278. Pull: true,
  279. }))
  280. }
  281. func Delete(c *context.APIContext) {
  282. owner, repo := parseOwnerAndRepo(c)
  283. if c.Written() {
  284. return
  285. }
  286. if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
  287. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  288. return
  289. }
  290. if err := db.DeleteRepository(owner.ID, repo.ID); err != nil {
  291. c.Error(err, "delete repository")
  292. return
  293. }
  294. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  295. c.NoContent()
  296. }
  297. func ListForks(c *context.APIContext) {
  298. forks, err := c.Repo.Repository.GetForks()
  299. if err != nil {
  300. c.Error(err, "get forks")
  301. return
  302. }
  303. apiForks := make([]*api.Repository, len(forks))
  304. for i := range forks {
  305. if err := forks[i].GetOwner(); err != nil {
  306. c.Error(err, "get owner")
  307. return
  308. }
  309. apiForks[i] = forks[i].APIFormat(&api.Permission{
  310. Admin: c.User.IsAdminOfRepo(forks[i]),
  311. Push: c.User.IsWriterOfRepo(forks[i]),
  312. Pull: true,
  313. })
  314. }
  315. c.JSONSuccess(&apiForks)
  316. }
  317. func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
  318. _, repo := parseOwnerAndRepo(c)
  319. if c.Written() {
  320. return
  321. }
  322. if form.EnableIssues != nil {
  323. repo.EnableIssues = *form.EnableIssues
  324. }
  325. if form.EnableExternalTracker != nil {
  326. repo.EnableExternalTracker = *form.EnableExternalTracker
  327. }
  328. if form.ExternalTrackerURL != nil {
  329. repo.ExternalTrackerURL = *form.ExternalTrackerURL
  330. }
  331. if form.TrackerURLFormat != nil {
  332. repo.ExternalTrackerFormat = *form.TrackerURLFormat
  333. }
  334. if form.TrackerIssueStyle != nil {
  335. repo.ExternalTrackerStyle = *form.TrackerIssueStyle
  336. }
  337. if err := db.UpdateRepository(repo, false); err != nil {
  338. c.Error(err, "update repository")
  339. return
  340. }
  341. c.NoContent()
  342. }
  343. func MirrorSync(c *context.APIContext) {
  344. _, repo := parseOwnerAndRepo(c)
  345. if c.Written() {
  346. return
  347. } else if !repo.IsMirror {
  348. c.NotFound()
  349. return
  350. }
  351. go db.MirrorQueue.Add(repo.ID)
  352. c.Status(http.StatusAccepted)
  353. }
  354. func Releases(c *context.APIContext) {
  355. _, repo := parseOwnerAndRepo(c)
  356. releases, err := db.GetReleasesByRepoID(repo.ID)
  357. if err != nil {
  358. c.Error(err, "get releases by repository ID")
  359. return
  360. }
  361. apiReleases := make([]*api.Release, 0, len(releases))
  362. for _, r := range releases {
  363. publisher, err := db.GetUserByID(r.PublisherID)
  364. if err != nil {
  365. c.Error(err, "get release publisher")
  366. return
  367. }
  368. r.Publisher = publisher
  369. }
  370. for _, r := range releases {
  371. apiReleases = append(apiReleases, r.APIFormat())
  372. }
  373. c.JSONSuccess(&apiReleases)
  374. }