org_team.go 17 KB

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