Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

org_team.go 15KB

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