You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

672 lines
15 KiB

  1. // Copyright 2016 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 models
  5. import (
  6. "errors"
  7. "fmt"
  8. "strings"
  9. )
  10. const ownerTeamName = "Owners"
  11. // Team represents a organization team.
  12. type Team struct {
  13. ID int64 `xorm:"pk autoincr"`
  14. OrgID int64 `xorm:"INDEX"`
  15. LowerName string
  16. Name string
  17. Description string
  18. Authorize AccessMode
  19. Repos []*Repository `xorm:"-"`
  20. Members []*User `xorm:"-"`
  21. NumRepos int
  22. NumMembers int
  23. }
  24. // IsOwnerTeam returns true if team is owner team.
  25. func (t *Team) IsOwnerTeam() bool {
  26. return t.Name == ownerTeamName
  27. }
  28. // IsMember returns true if given user is a member of team.
  29. func (t *Team) IsMember(userID int64) bool {
  30. return IsTeamMember(t.OrgID, t.ID, userID)
  31. }
  32. func (t *Team) getRepositories(e Engine) (err error) {
  33. teamRepos := make([]*TeamRepo, 0, t.NumRepos)
  34. if err = x.
  35. Where("team_id=?", t.ID).
  36. Find(&teamRepos); err != nil {
  37. return fmt.Errorf("get team-repos: %v", err)
  38. }
  39. t.Repos = make([]*Repository, 0, len(teamRepos))
  40. for i := range teamRepos {
  41. repo, err := getRepositoryByID(e, teamRepos[i].RepoID)
  42. if err != nil {
  43. return fmt.Errorf("getRepositoryById(%d): %v", teamRepos[i].RepoID, err)
  44. }
  45. t.Repos = append(t.Repos, repo)
  46. }
  47. return nil
  48. }
  49. // GetRepositories returns all repositories in team of organization.
  50. func (t *Team) GetRepositories() error {
  51. return t.getRepositories(x)
  52. }
  53. func (t *Team) getMembers(e Engine) (err error) {
  54. t.Members, err = getTeamMembers(e, t.ID)
  55. return err
  56. }
  57. // GetMembers returns all members in team of organization.
  58. func (t *Team) GetMembers() (err error) {
  59. return t.getMembers(x)
  60. }
  61. // AddMember adds new membership of the team to the organization,
  62. // the user will have membership to the organization automatically when needed.
  63. func (t *Team) AddMember(userID int64) error {
  64. return AddTeamMember(t.OrgID, t.ID, userID)
  65. }
  66. // RemoveMember removes member from team of organization.
  67. func (t *Team) RemoveMember(userID int64) error {
  68. return RemoveTeamMember(t.OrgID, t.ID, userID)
  69. }
  70. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  71. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  72. }
  73. // HasRepository returns true if given repository belong to team.
  74. func (t *Team) HasRepository(repoID int64) bool {
  75. return t.hasRepository(x, repoID)
  76. }
  77. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  78. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  79. return err
  80. }
  81. t.NumRepos++
  82. if _, err = e.Id(t.ID).AllCols().Update(t); err != nil {
  83. return fmt.Errorf("update team: %v", err)
  84. }
  85. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  86. return fmt.Errorf("recalculateAccesses: %v", err)
  87. }
  88. if err = t.getMembers(e); err != nil {
  89. return fmt.Errorf("getMembers: %v", err)
  90. }
  91. for _, u := range t.Members {
  92. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  93. return fmt.Errorf("watchRepo: %v", err)
  94. }
  95. }
  96. return nil
  97. }
  98. // AddRepository adds new repository to team of organization.
  99. func (t *Team) AddRepository(repo *Repository) (err error) {
  100. if repo.OwnerID != t.OrgID {
  101. return errors.New("Repository does not belong to organization")
  102. } else if t.HasRepository(repo.ID) {
  103. return nil
  104. }
  105. sess := x.NewSession()
  106. defer sessionRelease(sess)
  107. if err = sess.Begin(); err != nil {
  108. return err
  109. }
  110. if err = t.addRepository(sess, repo); err != nil {
  111. return err
  112. }
  113. return sess.Commit()
  114. }
  115. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  116. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  117. return err
  118. }
  119. t.NumRepos--
  120. if _, err = e.Id(t.ID).AllCols().Update(t); err != nil {
  121. return err
  122. }
  123. // Don't need to recalculate when delete a repository from organization.
  124. if recalculate {
  125. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  126. return err
  127. }
  128. }
  129. if err = t.getMembers(e); err != nil {
  130. return fmt.Errorf("get team members: %v", err)
  131. }
  132. for _, u := range t.Members {
  133. has, err := hasAccess(e, u, repo, AccessModeRead)
  134. if err != nil {
  135. return err
  136. } else if has {
  137. continue
  138. }
  139. if err = watchRepo(e, u.ID, repo.ID, false); err != nil {
  140. return err
  141. }
  142. }
  143. return nil
  144. }
  145. // RemoveRepository removes repository from team of organization.
  146. func (t *Team) RemoveRepository(repoID int64) error {
  147. if !t.HasRepository(repoID) {
  148. return nil
  149. }
  150. repo, err := GetRepositoryByID(repoID)
  151. if err != nil {
  152. return err
  153. }
  154. sess := x.NewSession()
  155. defer sessionRelease(sess)
  156. if err = sess.Begin(); err != nil {
  157. return err
  158. }
  159. if err = t.removeRepository(sess, repo, true); err != nil {
  160. return err
  161. }
  162. return sess.Commit()
  163. }
  164. // IsUsableTeamName tests if a name could be as team name
  165. func IsUsableTeamName(name string) (err error) {
  166. var reservedTeamNames = []string{"new"}
  167. for i := range reservedTeamNames {
  168. if name == reservedTeamNames[i] {
  169. return ErrNameReserved{name}
  170. }
  171. }
  172. return nil
  173. }
  174. // NewTeam creates a record of new team.
  175. // It's caller's responsibility to assign organization ID.
  176. func NewTeam(t *Team) (err error) {
  177. if len(t.Name) == 0 {
  178. return errors.New("empty team name")
  179. }
  180. if err = IsUsableTeamName(t.Name); err != nil {
  181. return err
  182. }
  183. has, err := x.Id(t.OrgID).Get(new(User))
  184. if err != nil {
  185. return err
  186. } else if !has {
  187. return ErrOrgNotExist
  188. }
  189. t.LowerName = strings.ToLower(t.Name)
  190. has, err = x.
  191. Where("org_id=?", t.OrgID).
  192. And("lower_name=?", t.LowerName).
  193. Get(new(Team))
  194. if err != nil {
  195. return err
  196. } else if has {
  197. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  198. }
  199. sess := x.NewSession()
  200. defer sess.Close()
  201. if err = sess.Begin(); err != nil {
  202. return err
  203. }
  204. if _, err = sess.Insert(t); err != nil {
  205. sess.Rollback()
  206. return err
  207. }
  208. // Update organization number of teams.
  209. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  210. sess.Rollback()
  211. return err
  212. }
  213. return sess.Commit()
  214. }
  215. func getTeam(e Engine, orgID int64, name string) (*Team, error) {
  216. t := &Team{
  217. OrgID: orgID,
  218. LowerName: strings.ToLower(name),
  219. }
  220. has, err := e.Get(t)
  221. if err != nil {
  222. return nil, err
  223. } else if !has {
  224. return nil, ErrTeamNotExist
  225. }
  226. return t, nil
  227. }
  228. // GetTeam returns team by given team name and organization.
  229. func GetTeam(orgID int64, name string) (*Team, error) {
  230. return getTeam(x, orgID, name)
  231. }
  232. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  233. t := new(Team)
  234. has, err := e.Id(teamID).Get(t)
  235. if err != nil {
  236. return nil, err
  237. } else if !has {
  238. return nil, ErrTeamNotExist
  239. }
  240. return t, nil
  241. }
  242. // GetTeamByID returns team by given ID.
  243. func GetTeamByID(teamID int64) (*Team, error) {
  244. return getTeamByID(x, teamID)
  245. }
  246. // UpdateTeam updates information of team.
  247. func UpdateTeam(t *Team, authChanged bool) (err error) {
  248. if len(t.Name) == 0 {
  249. return errors.New("empty team name")
  250. }
  251. if len(t.Description) > 255 {
  252. t.Description = t.Description[:255]
  253. }
  254. sess := x.NewSession()
  255. defer sessionRelease(sess)
  256. if err = sess.Begin(); err != nil {
  257. return err
  258. }
  259. t.LowerName = strings.ToLower(t.Name)
  260. has, err := sess.
  261. Where("org_id=?", t.OrgID).
  262. And("lower_name=?", t.LowerName).
  263. And("id!=?", t.ID).
  264. Get(new(Team))
  265. if err != nil {
  266. return err
  267. } else if has {
  268. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  269. }
  270. if _, err = sess.Id(t.ID).AllCols().Update(t); err != nil {
  271. return fmt.Errorf("update: %v", err)
  272. }
  273. // Update access for team members if needed.
  274. if authChanged {
  275. if err = t.getRepositories(sess); err != nil {
  276. return fmt.Errorf("getRepositories:%v", err)
  277. }
  278. for _, repo := range t.Repos {
  279. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  280. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  281. }
  282. }
  283. }
  284. return sess.Commit()
  285. }
  286. // DeleteTeam deletes given team.
  287. // It's caller's responsibility to assign organization ID.
  288. func DeleteTeam(t *Team) error {
  289. if err := t.GetRepositories(); err != nil {
  290. return err
  291. }
  292. // Get organization.
  293. org, err := GetUserByID(t.OrgID)
  294. if err != nil {
  295. return err
  296. }
  297. sess := x.NewSession()
  298. defer sessionRelease(sess)
  299. if err = sess.Begin(); err != nil {
  300. return err
  301. }
  302. // Delete all accesses.
  303. for _, repo := range t.Repos {
  304. if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  305. return err
  306. }
  307. }
  308. // Delete team-user.
  309. if _, err = sess.
  310. Where("org_id=?", org.ID).
  311. Where("team_id=?", t.ID).
  312. Delete(new(TeamUser)); err != nil {
  313. return err
  314. }
  315. // Delete team.
  316. if _, err = sess.Id(t.ID).Delete(new(Team)); err != nil {
  317. return err
  318. }
  319. // Update organization number of teams.
  320. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  321. return err
  322. }
  323. return sess.Commit()
  324. }
  325. // ___________ ____ ___
  326. // \__ ___/___ _____ _____ | | \______ ___________
  327. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  328. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  329. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  330. // \/ \/ \/ \/ \/
  331. // TeamUser represents an team-user relation.
  332. type TeamUser struct {
  333. ID int64 `xorm:"pk autoincr"`
  334. OrgID int64 `xorm:"INDEX"`
  335. TeamID int64 `xorm:"UNIQUE(s)"`
  336. UID int64 `xorm:"UNIQUE(s)"`
  337. }
  338. func isTeamMember(e Engine, orgID, teamID, userID int64) bool {
  339. has, _ := e.
  340. Where("org_id=?", orgID).
  341. And("team_id=?", teamID).
  342. And("uid=?", userID).
  343. Get(new(TeamUser))
  344. return has
  345. }
  346. // IsTeamMember returns true if given user is a member of team.
  347. func IsTeamMember(orgID, teamID, userID int64) bool {
  348. return isTeamMember(x, orgID, teamID, userID)
  349. }
  350. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  351. teamUsers := make([]*TeamUser, 0, 10)
  352. if err = e.
  353. Where("team_id=?", teamID).
  354. Find(&teamUsers); err != nil {
  355. return nil, fmt.Errorf("get team-users: %v", err)
  356. }
  357. members := make([]*User, 0, len(teamUsers))
  358. for i := range teamUsers {
  359. member := new(User)
  360. if _, err = e.Id(teamUsers[i].UID).Get(member); err != nil {
  361. return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].UID, err)
  362. }
  363. members = append(members, member)
  364. }
  365. return members, nil
  366. }
  367. // GetTeamMembers returns all members in given team of organization.
  368. func GetTeamMembers(teamID int64) ([]*User, error) {
  369. return getTeamMembers(x, teamID)
  370. }
  371. func getUserTeams(e Engine, orgID, userID int64) ([]*Team, error) {
  372. tus := make([]*TeamUser, 0, 5)
  373. if err := e.
  374. Where("uid=?", userID).
  375. And("org_id=?", orgID).
  376. Find(&tus); err != nil {
  377. return nil, err
  378. }
  379. ts := make([]*Team, len(tus))
  380. for i, tu := range tus {
  381. t := new(Team)
  382. has, err := e.Id(tu.TeamID).Get(t)
  383. if err != nil {
  384. return nil, err
  385. } else if !has {
  386. return nil, ErrTeamNotExist
  387. }
  388. ts[i] = t
  389. }
  390. return ts, nil
  391. }
  392. // GetUserTeams returns all teams that user belongs to in given organization.
  393. func GetUserTeams(orgID, userID int64) ([]*Team, error) {
  394. return getUserTeams(x, orgID, userID)
  395. }
  396. // AddTeamMember adds new membership of given team to given organization,
  397. // the user will have membership to given organization automatically when needed.
  398. func AddTeamMember(orgID, teamID, userID int64) error {
  399. if IsTeamMember(orgID, teamID, userID) {
  400. return nil
  401. }
  402. if err := AddOrgUser(orgID, userID); err != nil {
  403. return err
  404. }
  405. // Get team and its repositories.
  406. t, err := GetTeamByID(teamID)
  407. if err != nil {
  408. return err
  409. }
  410. t.NumMembers++
  411. if err = t.GetRepositories(); err != nil {
  412. return err
  413. }
  414. sess := x.NewSession()
  415. defer sessionRelease(sess)
  416. if err = sess.Begin(); err != nil {
  417. return err
  418. }
  419. tu := &TeamUser{
  420. UID: userID,
  421. OrgID: orgID,
  422. TeamID: teamID,
  423. }
  424. if _, err = sess.Insert(tu); err != nil {
  425. return err
  426. } else if _, err = sess.Id(t.ID).Update(t); err != nil {
  427. return err
  428. }
  429. // Give access to team repositories.
  430. for _, repo := range t.Repos {
  431. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  432. return err
  433. }
  434. }
  435. // We make sure it exists before.
  436. ou := new(OrgUser)
  437. if _, err = sess.
  438. Where("uid = ?", userID).
  439. And("org_id = ?", orgID).
  440. Get(ou); err != nil {
  441. return err
  442. }
  443. ou.NumTeams++
  444. if t.IsOwnerTeam() {
  445. ou.IsOwner = true
  446. }
  447. if _, err = sess.Id(ou.ID).AllCols().Update(ou); err != nil {
  448. return err
  449. }
  450. return sess.Commit()
  451. }
  452. func removeTeamMember(e Engine, orgID, teamID, userID int64) error {
  453. if !isTeamMember(e, orgID, teamID, userID) {
  454. return nil
  455. }
  456. // Get team and its repositories.
  457. t, err := getTeamByID(e, teamID)
  458. if err != nil {
  459. return err
  460. }
  461. // Check if the user to delete is the last member in owner team.
  462. if t.IsOwnerTeam() && t.NumMembers == 1 {
  463. return ErrLastOrgOwner{UID: userID}
  464. }
  465. t.NumMembers--
  466. if err = t.getRepositories(e); err != nil {
  467. return err
  468. }
  469. // Get organization.
  470. org, err := getUserByID(e, orgID)
  471. if err != nil {
  472. return err
  473. }
  474. tu := &TeamUser{
  475. UID: userID,
  476. OrgID: orgID,
  477. TeamID: teamID,
  478. }
  479. if _, err := e.Delete(tu); err != nil {
  480. return err
  481. } else if _, err = e.
  482. Id(t.ID).
  483. AllCols().
  484. Update(t); err != nil {
  485. return err
  486. }
  487. // Delete access to team repositories.
  488. for _, repo := range t.Repos {
  489. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  490. return err
  491. }
  492. }
  493. // This must exist.
  494. ou := new(OrgUser)
  495. _, err = e.
  496. Where("uid = ?", userID).
  497. And("org_id = ?", org.ID).
  498. Get(ou)
  499. if err != nil {
  500. return err
  501. }
  502. ou.NumTeams--
  503. if t.IsOwnerTeam() {
  504. ou.IsOwner = false
  505. }
  506. if _, err = e.
  507. Id(ou.ID).
  508. AllCols().
  509. Update(ou); err != nil {
  510. return err
  511. }
  512. return nil
  513. }
  514. // RemoveTeamMember removes member from given team of given organization.
  515. func RemoveTeamMember(orgID, teamID, userID int64) error {
  516. sess := x.NewSession()
  517. defer sessionRelease(sess)
  518. if err := sess.Begin(); err != nil {
  519. return err
  520. }
  521. if err := removeTeamMember(sess, orgID, teamID, userID); err != nil {
  522. return err
  523. }
  524. return sess.Commit()
  525. }
  526. // ___________ __________
  527. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  528. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  529. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  530. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  531. // \/ \/ \/ \/ \/|__|
  532. // TeamRepo represents an team-repository relation.
  533. type TeamRepo struct {
  534. ID int64 `xorm:"pk autoincr"`
  535. OrgID int64 `xorm:"INDEX"`
  536. TeamID int64 `xorm:"UNIQUE(s)"`
  537. RepoID int64 `xorm:"UNIQUE(s)"`
  538. }
  539. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  540. has, _ := e.
  541. Where("org_id=?", orgID).
  542. And("team_id=?", teamID).
  543. And("repo_id=?", repoID).
  544. Get(new(TeamRepo))
  545. return has
  546. }
  547. // HasTeamRepo returns true if given repository belongs to team.
  548. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  549. return hasTeamRepo(x, orgID, teamID, repoID)
  550. }
  551. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  552. _, err := e.InsertOne(&TeamRepo{
  553. OrgID: orgID,
  554. TeamID: teamID,
  555. RepoID: repoID,
  556. })
  557. return err
  558. }
  559. // AddTeamRepo adds new repository relation to team.
  560. func AddTeamRepo(orgID, teamID, repoID int64) error {
  561. return addTeamRepo(x, orgID, teamID, repoID)
  562. }
  563. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  564. _, err := e.Delete(&TeamRepo{
  565. TeamID: teamID,
  566. RepoID: repoID,
  567. })
  568. return err
  569. }
  570. // RemoveTeamRepo deletes repository relation to team.
  571. func RemoveTeamRepo(teamID, repoID int64) error {
  572. return removeTeamRepo(x, teamID, repoID)
  573. }