org_team.go 16 KB

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