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.

671 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 OWNER_TEAM = "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 == OWNER_TEAM
  27. }
  28. // IsTeamMember returns true if given user is a member of team.
  29. func (t *Team) IsMember(uid int64) bool {
  30. return IsTeamMember(t.OrgID, t.ID, uid)
  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(uid int64) error {
  64. return AddTeamMember(t.OrgID, t.ID, uid)
  65. }
  66. // RemoveMember removes member from team of organization.
  67. func (t *Team) RemoveMember(uid int64) error {
  68. return RemoveTeamMember(t.OrgID, t.ID, uid)
  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. func IsUsableTeamName(name string) (err error) {
  165. var reservedTeamNames = []string{"new"}
  166. for i := range reservedTeamNames {
  167. if name == reservedTeamNames[i] {
  168. return ErrNameReserved{name}
  169. }
  170. }
  171. return nil
  172. }
  173. // NewTeam creates a record of new team.
  174. // It's caller's responsibility to assign organization ID.
  175. func NewTeam(t *Team) (err error) {
  176. if len(t.Name) == 0 {
  177. return errors.New("empty team name")
  178. }
  179. if err = IsUsableTeamName(t.Name); err != nil {
  180. return err
  181. }
  182. has, err := x.Id(t.OrgID).Get(new(User))
  183. if err != nil {
  184. return err
  185. } else if !has {
  186. return ErrOrgNotExist
  187. }
  188. t.LowerName = strings.ToLower(t.Name)
  189. has, err = x.
  190. Where("org_id=?", t.OrgID).
  191. And("lower_name=?", t.LowerName).
  192. Get(new(Team))
  193. if err != nil {
  194. return err
  195. } else if has {
  196. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  197. }
  198. sess := x.NewSession()
  199. defer sess.Close()
  200. if err = sess.Begin(); err != nil {
  201. return err
  202. }
  203. if _, err = sess.Insert(t); err != nil {
  204. sess.Rollback()
  205. return err
  206. }
  207. // Update organization number of teams.
  208. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  209. sess.Rollback()
  210. return err
  211. }
  212. return sess.Commit()
  213. }
  214. func getTeam(e Engine, orgId int64, name string) (*Team, error) {
  215. t := &Team{
  216. OrgID: orgId,
  217. LowerName: strings.ToLower(name),
  218. }
  219. has, err := e.Get(t)
  220. if err != nil {
  221. return nil, err
  222. } else if !has {
  223. return nil, ErrTeamNotExist
  224. }
  225. return t, nil
  226. }
  227. // GetTeam returns team by given team name and organization.
  228. func GetTeam(orgId int64, name string) (*Team, error) {
  229. return getTeam(x, orgId, name)
  230. }
  231. func getTeamByID(e Engine, teamId int64) (*Team, error) {
  232. t := new(Team)
  233. has, err := e.Id(teamId).Get(t)
  234. if err != nil {
  235. return nil, err
  236. } else if !has {
  237. return nil, ErrTeamNotExist
  238. }
  239. return t, nil
  240. }
  241. // GetTeamByID returns team by given ID.
  242. func GetTeamByID(teamId int64) (*Team, error) {
  243. return getTeamByID(x, teamId)
  244. }
  245. // UpdateTeam updates information of team.
  246. func UpdateTeam(t *Team, authChanged bool) (err error) {
  247. if len(t.Name) == 0 {
  248. return errors.New("empty team name")
  249. }
  250. if len(t.Description) > 255 {
  251. t.Description = t.Description[:255]
  252. }
  253. sess := x.NewSession()
  254. defer sessionRelease(sess)
  255. if err = sess.Begin(); err != nil {
  256. return err
  257. }
  258. t.LowerName = strings.ToLower(t.Name)
  259. has, err := x.
  260. Where("org_id=?", t.OrgID).
  261. And("lower_name=?", t.LowerName).
  262. And("id!=?", t.ID).
  263. Get(new(Team))
  264. if err != nil {
  265. return err
  266. } else if has {
  267. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  268. }
  269. if _, err = sess.Id(t.ID).AllCols().Update(t); err != nil {
  270. return fmt.Errorf("update: %v", err)
  271. }
  272. // Update access for team members if needed.
  273. if authChanged {
  274. if err = t.getRepositories(sess); err != nil {
  275. return fmt.Errorf("getRepositories:%v", err)
  276. }
  277. for _, repo := range t.Repos {
  278. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  279. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  280. }
  281. }
  282. }
  283. return sess.Commit()
  284. }
  285. // DeleteTeam deletes given team.
  286. // It's caller's responsibility to assign organization ID.
  287. func DeleteTeam(t *Team) error {
  288. if err := t.GetRepositories(); err != nil {
  289. return err
  290. }
  291. // Get organization.
  292. org, err := GetUserByID(t.OrgID)
  293. if err != nil {
  294. return err
  295. }
  296. sess := x.NewSession()
  297. defer sessionRelease(sess)
  298. if err = sess.Begin(); err != nil {
  299. return err
  300. }
  301. // Delete all accesses.
  302. for _, repo := range t.Repos {
  303. if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  304. return err
  305. }
  306. }
  307. // Delete team-user.
  308. if _, err = sess.
  309. Where("org_id=?", org.ID).
  310. Where("team_id=?", t.ID).
  311. Delete(new(TeamUser)); err != nil {
  312. return err
  313. }
  314. // Delete team.
  315. if _, err = sess.Id(t.ID).Delete(new(Team)); err != nil {
  316. return err
  317. }
  318. // Update organization number of teams.
  319. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  320. return err
  321. }
  322. return sess.Commit()
  323. }
  324. // ___________ ____ ___
  325. // \__ ___/___ _____ _____ | | \______ ___________
  326. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  327. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  328. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  329. // \/ \/ \/ \/ \/
  330. // TeamUser represents an team-user relation.
  331. type TeamUser struct {
  332. ID int64 `xorm:"pk autoincr"`
  333. OrgID int64 `xorm:"INDEX"`
  334. TeamID int64 `xorm:"UNIQUE(s)"`
  335. Uid int64 `xorm:"UNIQUE(s)"`
  336. }
  337. func isTeamMember(e Engine, orgID, teamID, uid int64) bool {
  338. has, _ := e.
  339. Where("org_id=?", orgID).
  340. And("team_id=?", teamID).
  341. And("uid=?", uid).
  342. Get(new(TeamUser))
  343. return has
  344. }
  345. // IsTeamMember returns true if given user is a member of team.
  346. func IsTeamMember(orgID, teamID, uid int64) bool {
  347. return isTeamMember(x, orgID, teamID, uid)
  348. }
  349. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  350. teamUsers := make([]*TeamUser, 0, 10)
  351. if err = e.
  352. Where("team_id=?", teamID).
  353. Find(&teamUsers); err != nil {
  354. return nil, fmt.Errorf("get team-users: %v", err)
  355. }
  356. members := make([]*User, 0, len(teamUsers))
  357. for i := range teamUsers {
  358. member := new(User)
  359. if _, err = e.Id(teamUsers[i].Uid).Get(member); err != nil {
  360. return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].Uid, err)
  361. }
  362. members = append(members, member)
  363. }
  364. return members, nil
  365. }
  366. // GetTeamMembers returns all members in given team of organization.
  367. func GetTeamMembers(teamID int64) ([]*User, error) {
  368. return getTeamMembers(x, teamID)
  369. }
  370. func getUserTeams(e Engine, orgId, uid int64) ([]*Team, error) {
  371. tus := make([]*TeamUser, 0, 5)
  372. if err := e.
  373. Where("uid=?", uid).
  374. And("org_id=?", orgId).
  375. Find(&tus); err != nil {
  376. return nil, err
  377. }
  378. ts := make([]*Team, len(tus))
  379. for i, tu := range tus {
  380. t := new(Team)
  381. has, err := e.Id(tu.TeamID).Get(t)
  382. if err != nil {
  383. return nil, err
  384. } else if !has {
  385. return nil, ErrTeamNotExist
  386. }
  387. ts[i] = t
  388. }
  389. return ts, nil
  390. }
  391. // GetUserTeams returns all teams that user belongs to in given organization.
  392. func GetUserTeams(orgId, uid int64) ([]*Team, error) {
  393. return getUserTeams(x, orgId, uid)
  394. }
  395. // AddTeamMember adds new membership of given team to given organization,
  396. // the user will have membership to given organization automatically when needed.
  397. func AddTeamMember(orgID, teamID, uid int64) error {
  398. if IsTeamMember(orgID, teamID, uid) {
  399. return nil
  400. }
  401. if err := AddOrgUser(orgID, uid); err != nil {
  402. return err
  403. }
  404. // Get team and its repositories.
  405. t, err := GetTeamByID(teamID)
  406. if err != nil {
  407. return err
  408. }
  409. t.NumMembers++
  410. if err = t.GetRepositories(); err != nil {
  411. return err
  412. }
  413. sess := x.NewSession()
  414. defer sessionRelease(sess)
  415. if err = sess.Begin(); err != nil {
  416. return err
  417. }
  418. tu := &TeamUser{
  419. Uid: uid,
  420. OrgID: orgID,
  421. TeamID: teamID,
  422. }
  423. if _, err = sess.Insert(tu); err != nil {
  424. return err
  425. } else if _, err = sess.Id(t.ID).Update(t); err != nil {
  426. return err
  427. }
  428. // Give access to team repositories.
  429. for _, repo := range t.Repos {
  430. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  431. return err
  432. }
  433. }
  434. // We make sure it exists before.
  435. ou := new(OrgUser)
  436. if _, err = sess.
  437. Where("uid = ?", uid).
  438. And("org_id = ?", orgID).
  439. Get(ou); err != nil {
  440. return err
  441. }
  442. ou.NumTeams++
  443. if t.IsOwnerTeam() {
  444. ou.IsOwner = true
  445. }
  446. if _, err = sess.Id(ou.ID).AllCols().Update(ou); err != nil {
  447. return err
  448. }
  449. return sess.Commit()
  450. }
  451. func removeTeamMember(e Engine, orgID, teamID, uid int64) error {
  452. if !isTeamMember(e, orgID, teamID, uid) {
  453. return nil
  454. }
  455. // Get team and its repositories.
  456. t, err := getTeamByID(e, teamID)
  457. if err != nil {
  458. return err
  459. }
  460. // Check if the user to delete is the last member in owner team.
  461. if t.IsOwnerTeam() && t.NumMembers == 1 {
  462. return ErrLastOrgOwner{UID: uid}
  463. }
  464. t.NumMembers--
  465. if err = t.getRepositories(e); err != nil {
  466. return err
  467. }
  468. // Get organization.
  469. org, err := getUserByID(e, orgID)
  470. if err != nil {
  471. return err
  472. }
  473. tu := &TeamUser{
  474. Uid: uid,
  475. OrgID: orgID,
  476. TeamID: teamID,
  477. }
  478. if _, err := e.Delete(tu); err != nil {
  479. return err
  480. } else if _, err = e.
  481. Id(t.ID).
  482. AllCols().
  483. Update(t); err != nil {
  484. return err
  485. }
  486. // Delete access to team repositories.
  487. for _, repo := range t.Repos {
  488. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  489. return err
  490. }
  491. }
  492. // This must exist.
  493. ou := new(OrgUser)
  494. _, err = e.
  495. Where("uid = ?", uid).
  496. And("org_id = ?", org.ID).
  497. Get(ou)
  498. if err != nil {
  499. return err
  500. }
  501. ou.NumTeams--
  502. if t.IsOwnerTeam() {
  503. ou.IsOwner = false
  504. }
  505. if _, err = e.
  506. Id(ou.ID).
  507. AllCols().
  508. Update(ou); err != nil {
  509. return err
  510. }
  511. return nil
  512. }
  513. // RemoveTeamMember removes member from given team of given organization.
  514. func RemoveTeamMember(orgID, teamID, uid int64) error {
  515. sess := x.NewSession()
  516. defer sessionRelease(sess)
  517. if err := sess.Begin(); err != nil {
  518. return err
  519. }
  520. if err := removeTeamMember(sess, orgID, teamID, uid); err != nil {
  521. return err
  522. }
  523. return sess.Commit()
  524. }
  525. // ___________ __________
  526. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  527. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  528. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  529. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  530. // \/ \/ \/ \/ \/|__|
  531. // TeamRepo represents an team-repository relation.
  532. type TeamRepo struct {
  533. ID int64 `xorm:"pk autoincr"`
  534. OrgID int64 `xorm:"INDEX"`
  535. TeamID int64 `xorm:"UNIQUE(s)"`
  536. RepoID int64 `xorm:"UNIQUE(s)"`
  537. }
  538. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  539. has, _ := e.
  540. Where("org_id=?", orgID).
  541. And("team_id=?", teamID).
  542. And("repo_id=?", repoID).
  543. Get(new(TeamRepo))
  544. return has
  545. }
  546. // HasTeamRepo returns true if given repository belongs to team.
  547. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  548. return hasTeamRepo(x, orgID, teamID, repoID)
  549. }
  550. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  551. _, err := e.InsertOne(&TeamRepo{
  552. OrgID: orgID,
  553. TeamID: teamID,
  554. RepoID: repoID,
  555. })
  556. return err
  557. }
  558. // AddTeamRepo adds new repository relation to team.
  559. func AddTeamRepo(orgID, teamID, repoID int64) error {
  560. return addTeamRepo(x, orgID, teamID, repoID)
  561. }
  562. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  563. _, err := e.Delete(&TeamRepo{
  564. TeamID: teamID,
  565. RepoID: repoID,
  566. })
  567. return err
  568. }
  569. // RemoveTeamRepo deletes repository relation to team.
  570. func RemoveTeamRepo(teamID, repoID int64) error {
  571. return removeTeamRepo(x, teamID, repoID)
  572. }