org_team.go 16 KB

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