本站源代码
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.

937 lines
22KB

  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2016 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "errors"
  8. "fmt"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "xorm.io/builder"
  14. "xorm.io/xorm"
  15. )
  16. const ownerTeamName = "Owners"
  17. // Team represents a organization team.
  18. type Team struct {
  19. ID int64 `xorm:"pk autoincr"`
  20. OrgID int64 `xorm:"INDEX"`
  21. LowerName string
  22. Name string
  23. Description string
  24. Authorize AccessMode
  25. Repos []*Repository `xorm:"-"`
  26. Members []*User `xorm:"-"`
  27. NumRepos int
  28. NumMembers int
  29. Units []*TeamUnit `xorm:"-"`
  30. }
  31. // SearchTeamOptions holds the search options
  32. type SearchTeamOptions struct {
  33. UserID int64
  34. Keyword string
  35. OrgID int64
  36. IncludeDesc bool
  37. PageSize int
  38. Page int
  39. }
  40. // SearchTeam search for teams. Caller is responsible to check permissions.
  41. func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) {
  42. if opts.Page <= 0 {
  43. opts.Page = 1
  44. }
  45. if opts.PageSize == 0 {
  46. // Default limit
  47. opts.PageSize = 10
  48. }
  49. var cond = builder.NewCond()
  50. if len(opts.Keyword) > 0 {
  51. lowerKeyword := strings.ToLower(opts.Keyword)
  52. var keywordCond builder.Cond = builder.Like{"lower_name", lowerKeyword}
  53. if opts.IncludeDesc {
  54. keywordCond = keywordCond.Or(builder.Like{"LOWER(description)", lowerKeyword})
  55. }
  56. cond = cond.And(keywordCond)
  57. }
  58. cond = cond.And(builder.Eq{"org_id": opts.OrgID})
  59. sess := x.NewSession()
  60. defer sess.Close()
  61. count, err := sess.
  62. Where(cond).
  63. Count(new(Team))
  64. if err != nil {
  65. return nil, 0, err
  66. }
  67. sess = sess.Where(cond)
  68. if opts.PageSize == -1 {
  69. opts.PageSize = int(count)
  70. } else {
  71. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  72. }
  73. teams := make([]*Team, 0, opts.PageSize)
  74. if err = sess.
  75. OrderBy("lower_name").
  76. Find(&teams); err != nil {
  77. return nil, 0, err
  78. }
  79. return teams, count, nil
  80. }
  81. // ColorFormat provides a basic color format for a Team
  82. func (t *Team) ColorFormat(s fmt.State) {
  83. log.ColorFprintf(s, "%d:%s (OrgID: %d) %-v",
  84. log.NewColoredIDValue(t.ID),
  85. t.Name,
  86. log.NewColoredIDValue(t.OrgID),
  87. t.Authorize)
  88. }
  89. // GetUnits return a list of available units for a team
  90. func (t *Team) GetUnits() error {
  91. return t.getUnits(x)
  92. }
  93. func (t *Team) getUnits(e Engine) (err error) {
  94. if t.Units != nil {
  95. return nil
  96. }
  97. t.Units, err = getUnitsByTeamID(e, t.ID)
  98. return err
  99. }
  100. // GetUnitNames returns the team units names
  101. func (t *Team) GetUnitNames() (res []string) {
  102. for _, u := range t.Units {
  103. res = append(res, Units[u.Type].NameKey)
  104. }
  105. return
  106. }
  107. // HasWriteAccess returns true if team has at least write level access mode.
  108. func (t *Team) HasWriteAccess() bool {
  109. return t.Authorize >= AccessModeWrite
  110. }
  111. // IsOwnerTeam returns true if team is owner team.
  112. func (t *Team) IsOwnerTeam() bool {
  113. return t.Name == ownerTeamName
  114. }
  115. // IsMember returns true if given user is a member of team.
  116. func (t *Team) IsMember(userID int64) bool {
  117. isMember, err := IsTeamMember(t.OrgID, t.ID, userID)
  118. if err != nil {
  119. log.Error("IsMember: %v", err)
  120. return false
  121. }
  122. return isMember
  123. }
  124. func (t *Team) getRepositories(e Engine) error {
  125. return e.Join("INNER", "team_repo", "repository.id = team_repo.repo_id").
  126. Where("team_repo.team_id=?", t.ID).
  127. OrderBy("repository.name").
  128. Find(&t.Repos)
  129. }
  130. // GetRepositories returns all repositories in team of organization.
  131. func (t *Team) GetRepositories() error {
  132. return t.getRepositories(x)
  133. }
  134. func (t *Team) getMembers(e Engine) (err error) {
  135. t.Members, err = getTeamMembers(e, t.ID)
  136. return err
  137. }
  138. // GetMembers returns all members in team of organization.
  139. func (t *Team) GetMembers() (err error) {
  140. return t.getMembers(x)
  141. }
  142. // AddMember adds new membership of the team to the organization,
  143. // the user will have membership to the organization automatically when needed.
  144. func (t *Team) AddMember(userID int64) error {
  145. return AddTeamMember(t, userID)
  146. }
  147. // RemoveMember removes member from team of organization.
  148. func (t *Team) RemoveMember(userID int64) error {
  149. return RemoveTeamMember(t, userID)
  150. }
  151. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  152. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  153. }
  154. // HasRepository returns true if given repository belong to team.
  155. func (t *Team) HasRepository(repoID int64) bool {
  156. return t.hasRepository(x, repoID)
  157. }
  158. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  159. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  160. return err
  161. }
  162. if _, err = e.Incr("num_repos").ID(t.ID).Update(new(Team)); err != nil {
  163. return fmt.Errorf("update team: %v", err)
  164. }
  165. t.NumRepos++
  166. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  167. return fmt.Errorf("recalculateAccesses: %v", err)
  168. }
  169. // Make all team members watch this repo if enabled in global settings
  170. if setting.Service.AutoWatchNewRepos {
  171. if err = t.getMembers(e); err != nil {
  172. return fmt.Errorf("getMembers: %v", err)
  173. }
  174. for _, u := range t.Members {
  175. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  176. return fmt.Errorf("watchRepo: %v", err)
  177. }
  178. }
  179. }
  180. return nil
  181. }
  182. // AddRepository adds new repository to team of organization.
  183. func (t *Team) AddRepository(repo *Repository) (err error) {
  184. if repo.OwnerID != t.OrgID {
  185. return errors.New("Repository does not belong to organization")
  186. } else if t.HasRepository(repo.ID) {
  187. return nil
  188. }
  189. sess := x.NewSession()
  190. defer sess.Close()
  191. if err = sess.Begin(); err != nil {
  192. return err
  193. }
  194. if err = t.addRepository(sess, repo); err != nil {
  195. return err
  196. }
  197. return sess.Commit()
  198. }
  199. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  200. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  201. return err
  202. }
  203. t.NumRepos--
  204. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  205. return err
  206. }
  207. // Don't need to recalculate when delete a repository from organization.
  208. if recalculate {
  209. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  210. return err
  211. }
  212. }
  213. teamUsers, err := getTeamUsersByTeamID(e, t.ID)
  214. if err != nil {
  215. return fmt.Errorf("getTeamUsersByTeamID: %v", err)
  216. }
  217. for _, teamUser := range teamUsers {
  218. has, err := hasAccess(e, teamUser.UID, repo)
  219. if err != nil {
  220. return err
  221. } else if has {
  222. continue
  223. }
  224. if err = watchRepo(e, teamUser.UID, repo.ID, false); err != nil {
  225. return err
  226. }
  227. // Remove all IssueWatches a user has subscribed to in the repositories
  228. if err := removeIssueWatchersByRepoID(e, teamUser.UID, repo.ID); err != nil {
  229. return err
  230. }
  231. }
  232. return nil
  233. }
  234. // RemoveRepository removes repository from team of organization.
  235. func (t *Team) RemoveRepository(repoID int64) error {
  236. if !t.HasRepository(repoID) {
  237. return nil
  238. }
  239. repo, err := GetRepositoryByID(repoID)
  240. if err != nil {
  241. return err
  242. }
  243. sess := x.NewSession()
  244. defer sess.Close()
  245. if err = sess.Begin(); err != nil {
  246. return err
  247. }
  248. if err = t.removeRepository(sess, repo, true); err != nil {
  249. return err
  250. }
  251. return sess.Commit()
  252. }
  253. // UnitEnabled returns if the team has the given unit type enabled
  254. func (t *Team) UnitEnabled(tp UnitType) bool {
  255. return t.unitEnabled(x, tp)
  256. }
  257. func (t *Team) unitEnabled(e Engine, tp UnitType) bool {
  258. if err := t.getUnits(e); err != nil {
  259. log.Warn("Error loading team (ID: %d) units: %s", t.ID, err.Error())
  260. }
  261. for _, unit := range t.Units {
  262. if unit.Type == tp {
  263. return true
  264. }
  265. }
  266. return false
  267. }
  268. // IsUsableTeamName tests if a name could be as team name
  269. func IsUsableTeamName(name string) error {
  270. switch name {
  271. case "new":
  272. return ErrNameReserved{name}
  273. default:
  274. return nil
  275. }
  276. }
  277. // NewTeam creates a record of new team.
  278. // It's caller's responsibility to assign organization ID.
  279. func NewTeam(t *Team) (err error) {
  280. if len(t.Name) == 0 {
  281. return errors.New("empty team name")
  282. }
  283. if err = IsUsableTeamName(t.Name); err != nil {
  284. return err
  285. }
  286. has, err := x.ID(t.OrgID).Get(new(User))
  287. if err != nil {
  288. return err
  289. }
  290. if !has {
  291. return ErrOrgNotExist{t.OrgID, ""}
  292. }
  293. t.LowerName = strings.ToLower(t.Name)
  294. has, err = x.
  295. Where("org_id=?", t.OrgID).
  296. And("lower_name=?", t.LowerName).
  297. Get(new(Team))
  298. if err != nil {
  299. return err
  300. }
  301. if has {
  302. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  303. }
  304. sess := x.NewSession()
  305. defer sess.Close()
  306. if err = sess.Begin(); err != nil {
  307. return err
  308. }
  309. if _, err = sess.Insert(t); err != nil {
  310. errRollback := sess.Rollback()
  311. if errRollback != nil {
  312. log.Error("NewTeam sess.Rollback: %v", errRollback)
  313. }
  314. return err
  315. }
  316. // insert units for team
  317. if len(t.Units) > 0 {
  318. for _, unit := range t.Units {
  319. unit.TeamID = t.ID
  320. }
  321. if _, err = sess.Insert(&t.Units); err != nil {
  322. errRollback := sess.Rollback()
  323. if errRollback != nil {
  324. log.Error("NewTeam sess.Rollback: %v", errRollback)
  325. }
  326. return err
  327. }
  328. }
  329. // Update organization number of teams.
  330. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  331. errRollback := sess.Rollback()
  332. if errRollback != nil {
  333. log.Error("NewTeam sess.Rollback: %v", errRollback)
  334. }
  335. return err
  336. }
  337. return sess.Commit()
  338. }
  339. func getTeam(e Engine, orgID int64, name string) (*Team, error) {
  340. t := &Team{
  341. OrgID: orgID,
  342. LowerName: strings.ToLower(name),
  343. }
  344. has, err := e.Get(t)
  345. if err != nil {
  346. return nil, err
  347. } else if !has {
  348. return nil, ErrTeamNotExist{orgID, 0, name}
  349. }
  350. return t, nil
  351. }
  352. // GetTeam returns team by given team name and organization.
  353. func GetTeam(orgID int64, name string) (*Team, error) {
  354. return getTeam(x, orgID, name)
  355. }
  356. // getOwnerTeam returns team by given team name and organization.
  357. func getOwnerTeam(e Engine, orgID int64) (*Team, error) {
  358. return getTeam(e, orgID, ownerTeamName)
  359. }
  360. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  361. t := new(Team)
  362. has, err := e.ID(teamID).Get(t)
  363. if err != nil {
  364. return nil, err
  365. } else if !has {
  366. return nil, ErrTeamNotExist{0, teamID, ""}
  367. }
  368. return t, nil
  369. }
  370. // GetTeamByID returns team by given ID.
  371. func GetTeamByID(teamID int64) (*Team, error) {
  372. return getTeamByID(x, teamID)
  373. }
  374. // UpdateTeam updates information of team.
  375. func UpdateTeam(t *Team, authChanged bool) (err error) {
  376. if len(t.Name) == 0 {
  377. return errors.New("empty team name")
  378. }
  379. if len(t.Description) > 255 {
  380. t.Description = t.Description[:255]
  381. }
  382. sess := x.NewSession()
  383. defer sess.Close()
  384. if err = sess.Begin(); err != nil {
  385. return err
  386. }
  387. t.LowerName = strings.ToLower(t.Name)
  388. has, err := sess.
  389. Where("org_id=?", t.OrgID).
  390. And("lower_name=?", t.LowerName).
  391. And("id!=?", t.ID).
  392. Get(new(Team))
  393. if err != nil {
  394. return err
  395. } else if has {
  396. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  397. }
  398. if _, err = sess.ID(t.ID).AllCols().Update(t); err != nil {
  399. return fmt.Errorf("update: %v", err)
  400. }
  401. // update units for team
  402. if len(t.Units) > 0 {
  403. for _, unit := range t.Units {
  404. unit.TeamID = t.ID
  405. }
  406. // Delete team-unit.
  407. if _, err := sess.
  408. Where("team_id=?", t.ID).
  409. Delete(new(TeamUnit)); err != nil {
  410. return err
  411. }
  412. if _, err = sess.Insert(&t.Units); err != nil {
  413. errRollback := sess.Rollback()
  414. if errRollback != nil {
  415. log.Error("UpdateTeam sess.Rollback: %v", errRollback)
  416. }
  417. return err
  418. }
  419. }
  420. // Update access for team members if needed.
  421. if authChanged {
  422. if err = t.getRepositories(sess); err != nil {
  423. return fmt.Errorf("getRepositories: %v", err)
  424. }
  425. for _, repo := range t.Repos {
  426. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  427. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  428. }
  429. }
  430. }
  431. return sess.Commit()
  432. }
  433. // DeleteTeam deletes given team.
  434. // It's caller's responsibility to assign organization ID.
  435. func DeleteTeam(t *Team) error {
  436. if err := t.GetRepositories(); err != nil {
  437. return err
  438. }
  439. sess := x.NewSession()
  440. defer sess.Close()
  441. if err := sess.Begin(); err != nil {
  442. return err
  443. }
  444. if err := t.getMembers(sess); err != nil {
  445. return err
  446. }
  447. // Delete all accesses.
  448. for _, repo := range t.Repos {
  449. if err := repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  450. return err
  451. }
  452. // Remove watches from all users and now unaccessible repos
  453. for _, user := range t.Members {
  454. has, err := hasAccess(sess, user.ID, repo)
  455. if err != nil {
  456. return err
  457. } else if has {
  458. continue
  459. }
  460. if err = watchRepo(sess, user.ID, repo.ID, false); err != nil {
  461. return err
  462. }
  463. // Remove all IssueWatches a user has subscribed to in the repositories
  464. if err = removeIssueWatchersByRepoID(sess, user.ID, repo.ID); err != nil {
  465. return err
  466. }
  467. }
  468. }
  469. // Delete team-repo
  470. if _, err := sess.
  471. Where("team_id=?", t.ID).
  472. Delete(new(TeamRepo)); err != nil {
  473. return err
  474. }
  475. // Delete team-user.
  476. if _, err := sess.
  477. Where("org_id=?", t.OrgID).
  478. Where("team_id=?", t.ID).
  479. Delete(new(TeamUser)); err != nil {
  480. return err
  481. }
  482. // Delete team-unit.
  483. if _, err := sess.
  484. Where("team_id=?", t.ID).
  485. Delete(new(TeamUnit)); err != nil {
  486. return err
  487. }
  488. // Delete team.
  489. if _, err := sess.ID(t.ID).Delete(new(Team)); err != nil {
  490. return err
  491. }
  492. // Update organization number of teams.
  493. if _, err := sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  494. return err
  495. }
  496. return sess.Commit()
  497. }
  498. // ___________ ____ ___
  499. // \__ ___/___ _____ _____ | | \______ ___________
  500. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  501. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  502. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  503. // \/ \/ \/ \/ \/
  504. // TeamUser represents an team-user relation.
  505. type TeamUser struct {
  506. ID int64 `xorm:"pk autoincr"`
  507. OrgID int64 `xorm:"INDEX"`
  508. TeamID int64 `xorm:"UNIQUE(s)"`
  509. UID int64 `xorm:"UNIQUE(s)"`
  510. }
  511. func isTeamMember(e Engine, orgID, teamID, userID int64) (bool, error) {
  512. return e.
  513. Where("org_id=?", orgID).
  514. And("team_id=?", teamID).
  515. And("uid=?", userID).
  516. Table("team_user").
  517. Exist()
  518. }
  519. // IsTeamMember returns true if given user is a member of team.
  520. func IsTeamMember(orgID, teamID, userID int64) (bool, error) {
  521. return isTeamMember(x, orgID, teamID, userID)
  522. }
  523. func getTeamUsersByTeamID(e Engine, teamID int64) ([]*TeamUser, error) {
  524. teamUsers := make([]*TeamUser, 0, 10)
  525. return teamUsers, e.
  526. Where("team_id=?", teamID).
  527. Find(&teamUsers)
  528. }
  529. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  530. teamUsers, err := getTeamUsersByTeamID(e, teamID)
  531. if err != nil {
  532. return nil, fmt.Errorf("get team-users: %v", err)
  533. }
  534. members := make([]*User, len(teamUsers))
  535. for i, teamUser := range teamUsers {
  536. member, err := getUserByID(e, teamUser.UID)
  537. if err != nil {
  538. return nil, fmt.Errorf("get user '%d': %v", teamUser.UID, err)
  539. }
  540. members[i] = member
  541. }
  542. sort.Slice(members, func(i, j int) bool {
  543. return members[i].DisplayName() < members[j].DisplayName()
  544. })
  545. return members, nil
  546. }
  547. // GetTeamMembers returns all members in given team of organization.
  548. func GetTeamMembers(teamID int64) ([]*User, error) {
  549. return getTeamMembers(x, teamID)
  550. }
  551. func getUserTeams(e Engine, userID int64) (teams []*Team, err error) {
  552. return teams, e.
  553. Join("INNER", "team_user", "team_user.team_id = team.id").
  554. Where("team_user.uid=?", userID).
  555. Find(&teams)
  556. }
  557. func getUserOrgTeams(e Engine, orgID, userID int64) (teams []*Team, err error) {
  558. return teams, e.
  559. Join("INNER", "team_user", "team_user.team_id = team.id").
  560. Where("team.org_id = ?", orgID).
  561. And("team_user.uid=?", userID).
  562. Find(&teams)
  563. }
  564. func getUserRepoTeams(e Engine, orgID, userID, repoID int64) (teams []*Team, err error) {
  565. return teams, e.
  566. Join("INNER", "team_user", "team_user.team_id = team.id").
  567. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  568. Where("team.org_id = ?", orgID).
  569. And("team_user.uid=?", userID).
  570. And("team_repo.repo_id=?", repoID).
  571. Find(&teams)
  572. }
  573. // GetUserOrgTeams returns all teams that user belongs to in given organization.
  574. func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) {
  575. return getUserOrgTeams(x, orgID, userID)
  576. }
  577. // GetUserTeams returns all teams that user belongs across all organizations.
  578. func GetUserTeams(userID int64) ([]*Team, error) {
  579. return getUserTeams(x, userID)
  580. }
  581. // AddTeamMember adds new membership of given team to given organization,
  582. // the user will have membership to given organization automatically when needed.
  583. func AddTeamMember(team *Team, userID int64) error {
  584. isAlreadyMember, err := IsTeamMember(team.OrgID, team.ID, userID)
  585. if err != nil || isAlreadyMember {
  586. return err
  587. }
  588. if err := AddOrgUser(team.OrgID, userID); err != nil {
  589. return err
  590. }
  591. // Get team and its repositories.
  592. if err := team.GetRepositories(); err != nil {
  593. return err
  594. }
  595. sess := x.NewSession()
  596. defer sess.Close()
  597. if err := sess.Begin(); err != nil {
  598. return err
  599. }
  600. if _, err := sess.Insert(&TeamUser{
  601. UID: userID,
  602. OrgID: team.OrgID,
  603. TeamID: team.ID,
  604. }); err != nil {
  605. return err
  606. } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(Team)); err != nil {
  607. return err
  608. }
  609. team.NumMembers++
  610. // Give access to team repositories.
  611. for _, repo := range team.Repos {
  612. if err := repo.recalculateUserAccess(sess, userID); err != nil {
  613. return err
  614. }
  615. if setting.Service.AutoWatchNewRepos {
  616. if err = watchRepo(sess, userID, repo.ID, true); err != nil {
  617. return err
  618. }
  619. }
  620. }
  621. return sess.Commit()
  622. }
  623. func removeTeamMember(e *xorm.Session, team *Team, userID int64) error {
  624. isMember, err := isTeamMember(e, team.OrgID, team.ID, userID)
  625. if err != nil || !isMember {
  626. return err
  627. }
  628. // Check if the user to delete is the last member in owner team.
  629. if team.IsOwnerTeam() && team.NumMembers == 1 {
  630. return ErrLastOrgOwner{UID: userID}
  631. }
  632. team.NumMembers--
  633. if err := team.getRepositories(e); err != nil {
  634. return err
  635. }
  636. if _, err := e.Delete(&TeamUser{
  637. UID: userID,
  638. OrgID: team.OrgID,
  639. TeamID: team.ID,
  640. }); err != nil {
  641. return err
  642. } else if _, err = e.
  643. ID(team.ID).
  644. Cols("num_members").
  645. Update(team); err != nil {
  646. return err
  647. }
  648. // Delete access to team repositories.
  649. for _, repo := range team.Repos {
  650. if err := repo.recalculateUserAccess(e, userID); err != nil {
  651. return err
  652. }
  653. // Remove watches from now unaccessible
  654. has, err := hasAccess(e, userID, repo)
  655. if err != nil {
  656. return err
  657. } else if has {
  658. continue
  659. }
  660. if err = watchRepo(e, userID, repo.ID, false); err != nil {
  661. return err
  662. }
  663. // Remove all IssueWatches a user has subscribed to in the repositories
  664. if err := removeIssueWatchersByRepoID(e, userID, repo.ID); err != nil {
  665. return err
  666. }
  667. }
  668. // Check if the user is a member of any team in the organization.
  669. if count, err := e.Count(&TeamUser{
  670. UID: userID,
  671. OrgID: team.OrgID,
  672. }); err != nil {
  673. return err
  674. } else if count == 0 {
  675. return removeOrgUser(e, team.OrgID, userID)
  676. }
  677. return nil
  678. }
  679. // RemoveTeamMember removes member from given team of given organization.
  680. func RemoveTeamMember(team *Team, userID int64) error {
  681. sess := x.NewSession()
  682. defer sess.Close()
  683. if err := sess.Begin(); err != nil {
  684. return err
  685. }
  686. if err := removeTeamMember(sess, team, userID); err != nil {
  687. return err
  688. }
  689. return sess.Commit()
  690. }
  691. // IsUserInTeams returns if a user in some teams
  692. func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) {
  693. return x.Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser))
  694. }
  695. // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
  696. func UsersInTeamsCount(userIDs []int64, teamIDs []int64) (int64, error) {
  697. var ids []int64
  698. if err := x.In("uid", userIDs).In("team_id", teamIDs).
  699. Table("team_user").
  700. Cols("uid").GroupBy("uid").Find(&ids); err != nil {
  701. return 0, err
  702. }
  703. return int64(len(ids)), nil
  704. }
  705. // ___________ __________
  706. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  707. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  708. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  709. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  710. // \/ \/ \/ \/ \/|__|
  711. // TeamRepo represents an team-repository relation.
  712. type TeamRepo struct {
  713. ID int64 `xorm:"pk autoincr"`
  714. OrgID int64 `xorm:"INDEX"`
  715. TeamID int64 `xorm:"UNIQUE(s)"`
  716. RepoID int64 `xorm:"UNIQUE(s)"`
  717. }
  718. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  719. has, _ := e.
  720. Where("org_id=?", orgID).
  721. And("team_id=?", teamID).
  722. And("repo_id=?", repoID).
  723. Get(new(TeamRepo))
  724. return has
  725. }
  726. // HasTeamRepo returns true if given repository belongs to team.
  727. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  728. return hasTeamRepo(x, orgID, teamID, repoID)
  729. }
  730. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  731. _, err := e.InsertOne(&TeamRepo{
  732. OrgID: orgID,
  733. TeamID: teamID,
  734. RepoID: repoID,
  735. })
  736. return err
  737. }
  738. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  739. _, err := e.Delete(&TeamRepo{
  740. TeamID: teamID,
  741. RepoID: repoID,
  742. })
  743. return err
  744. }
  745. // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
  746. func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
  747. teams := make([]*Team, 0, 5)
  748. return teams, x.Where("team.authorize >= ?", mode).
  749. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  750. And("team_repo.org_id = ?", orgID).
  751. And("team_repo.repo_id = ?", repoID).
  752. Find(&teams)
  753. }
  754. // ___________ ____ ___ .__ __
  755. // \__ ___/___ _____ _____ | | \____ |__|/ |_
  756. // | |_/ __ \\__ \ / \| | / \| \ __\
  757. // | |\ ___/ / __ \| Y Y \ | / | \ || |
  758. // |____| \___ >____ /__|_| /______/|___| /__||__|
  759. // \/ \/ \/ \/
  760. // TeamUnit describes all units of a repository
  761. type TeamUnit struct {
  762. ID int64 `xorm:"pk autoincr"`
  763. OrgID int64 `xorm:"INDEX"`
  764. TeamID int64 `xorm:"UNIQUE(s)"`
  765. Type UnitType `xorm:"UNIQUE(s)"`
  766. }
  767. // Unit returns Unit
  768. func (t *TeamUnit) Unit() Unit {
  769. return Units[t.Type]
  770. }
  771. func getUnitsByTeamID(e Engine, teamID int64) (units []*TeamUnit, err error) {
  772. return units, e.Where("team_id = ?", teamID).Find(&units)
  773. }
  774. // UpdateTeamUnits updates a teams's units
  775. func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) {
  776. sess := x.NewSession()
  777. defer sess.Close()
  778. if err = sess.Begin(); err != nil {
  779. return err
  780. }
  781. if _, err = sess.Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil {
  782. return err
  783. }
  784. if _, err = sess.Insert(units); err != nil {
  785. errRollback := sess.Rollback()
  786. if errRollback != nil {
  787. log.Error("UpdateTeamUnits sess.Rollback: %v", errRollback)
  788. }
  789. return err
  790. }
  791. return sess.Commit()
  792. }
上海开阖软件有限公司 沪ICP备12045867号-1