org_team.go 15 KB

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