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

org_team.go 15KB

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