org_team.go 15 KB

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