repo.go 10 KB

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