org_team.go 16 KB

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