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

org_team.go 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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) (teams []*Team, err error) {
  372. return teams, e.
  373. Join("INNER", "team_user", "team_user.team_id = team.id").
  374. Where("team.org_id = ?", orgID).
  375. And("team_user.uid=?", userID).
  376. Find(&teams)
  377. }
  378. // GetUserTeams returns all teams that user belongs to in given organization.
  379. func GetUserTeams(orgID, userID int64) ([]*Team, error) {
  380. return getUserTeams(x, orgID, userID)
  381. }
  382. // AddTeamMember adds new membership of given team to given organization,
  383. // the user will have membership to given organization automatically when needed.
  384. func AddTeamMember(orgID, teamID, userID int64) error {
  385. if IsTeamMember(orgID, teamID, userID) {
  386. return nil
  387. }
  388. if err := AddOrgUser(orgID, userID); err != nil {
  389. return err
  390. }
  391. // Get team and its repositories.
  392. t, err := GetTeamByID(teamID)
  393. if err != nil {
  394. return err
  395. }
  396. t.NumMembers++
  397. if err = t.GetRepositories(); err != nil {
  398. return err
  399. }
  400. sess := x.NewSession()
  401. defer sessionRelease(sess)
  402. if err = sess.Begin(); err != nil {
  403. return err
  404. }
  405. tu := &TeamUser{
  406. UID: userID,
  407. OrgID: orgID,
  408. TeamID: teamID,
  409. }
  410. if _, err = sess.Insert(tu); err != nil {
  411. return err
  412. } else if _, err = sess.Id(t.ID).Update(t); err != nil {
  413. return err
  414. }
  415. // Give access to team repositories.
  416. for _, repo := range t.Repos {
  417. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  418. return err
  419. }
  420. }
  421. // We make sure it exists before.
  422. ou := new(OrgUser)
  423. if _, err = sess.
  424. Where("uid = ?", userID).
  425. And("org_id = ?", orgID).
  426. Get(ou); err != nil {
  427. return err
  428. }
  429. ou.NumTeams++
  430. if t.IsOwnerTeam() {
  431. ou.IsOwner = true
  432. }
  433. if _, err = sess.Id(ou.ID).AllCols().Update(ou); err != nil {
  434. return err
  435. }
  436. return sess.Commit()
  437. }
  438. func removeTeamMember(e Engine, orgID, teamID, userID int64) error {
  439. if !isTeamMember(e, orgID, teamID, userID) {
  440. return nil
  441. }
  442. // Get team and its repositories.
  443. t, err := getTeamByID(e, teamID)
  444. if err != nil {
  445. return err
  446. }
  447. // Check if the user to delete is the last member in owner team.
  448. if t.IsOwnerTeam() && t.NumMembers == 1 {
  449. return ErrLastOrgOwner{UID: userID}
  450. }
  451. t.NumMembers--
  452. if err = t.getRepositories(e); err != nil {
  453. return err
  454. }
  455. // Get organization.
  456. org, err := getUserByID(e, orgID)
  457. if err != nil {
  458. return err
  459. }
  460. tu := &TeamUser{
  461. UID: userID,
  462. OrgID: orgID,
  463. TeamID: teamID,
  464. }
  465. if _, err := e.Delete(tu); err != nil {
  466. return err
  467. } else if _, err = e.
  468. Id(t.ID).
  469. AllCols().
  470. Update(t); err != nil {
  471. return err
  472. }
  473. // Delete access to team repositories.
  474. for _, repo := range t.Repos {
  475. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  476. return err
  477. }
  478. }
  479. // This must exist.
  480. ou := new(OrgUser)
  481. _, err = e.
  482. Where("uid = ?", userID).
  483. And("org_id = ?", org.ID).
  484. Get(ou)
  485. if err != nil {
  486. return err
  487. }
  488. ou.NumTeams--
  489. if t.IsOwnerTeam() {
  490. ou.IsOwner = false
  491. }
  492. if _, err = e.
  493. Id(ou.ID).
  494. AllCols().
  495. Update(ou); err != nil {
  496. return err
  497. }
  498. return nil
  499. }
  500. // RemoveTeamMember removes member from given team of given organization.
  501. func RemoveTeamMember(orgID, teamID, userID int64) error {
  502. sess := x.NewSession()
  503. defer sessionRelease(sess)
  504. if err := sess.Begin(); err != nil {
  505. return err
  506. }
  507. if err := removeTeamMember(sess, orgID, teamID, userID); err != nil {
  508. return err
  509. }
  510. return sess.Commit()
  511. }
  512. // ___________ __________
  513. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  514. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  515. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  516. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  517. // \/ \/ \/ \/ \/|__|
  518. // TeamRepo represents an team-repository relation.
  519. type TeamRepo struct {
  520. ID int64 `xorm:"pk autoincr"`
  521. OrgID int64 `xorm:"INDEX"`
  522. TeamID int64 `xorm:"UNIQUE(s)"`
  523. RepoID int64 `xorm:"UNIQUE(s)"`
  524. }
  525. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  526. has, _ := e.
  527. Where("org_id=?", orgID).
  528. And("team_id=?", teamID).
  529. And("repo_id=?", repoID).
  530. Get(new(TeamRepo))
  531. return has
  532. }
  533. // HasTeamRepo returns true if given repository belongs to team.
  534. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  535. return hasTeamRepo(x, orgID, teamID, repoID)
  536. }
  537. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  538. _, err := e.InsertOne(&TeamRepo{
  539. OrgID: orgID,
  540. TeamID: teamID,
  541. RepoID: repoID,
  542. })
  543. return err
  544. }
  545. // AddTeamRepo adds new repository relation to team.
  546. func AddTeamRepo(orgID, teamID, repoID int64) error {
  547. return addTeamRepo(x, orgID, teamID, repoID)
  548. }
  549. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  550. _, err := e.Delete(&TeamRepo{
  551. TeamID: teamID,
  552. RepoID: repoID,
  553. })
  554. return err
  555. }
  556. // RemoveTeamRepo deletes repository relation to team.
  557. func RemoveTeamRepo(teamID, repoID int64) error {
  558. return removeTeamRepo(x, teamID, repoID)
  559. }