repo.go 10 KB

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