org_team.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. existingTeam := Team{}
  201. has, err = x.Where("org_id=?", t.OrgID).And("lower_name=?", t.LowerName).Get(&existingTeam)
  202. if err != nil {
  203. return err
  204. } else if has {
  205. return ErrTeamAlreadyExist{existingTeam.ID, t.OrgID, t.LowerName}
  206. }
  207. sess := x.NewSession()
  208. defer sess.Close()
  209. if err = sess.Begin(); err != nil {
  210. return err
  211. }
  212. if _, err = sess.Insert(t); err != nil {
  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. return err
  218. }
  219. return sess.Commit()
  220. }
  221. var _ errutil.NotFound = (*ErrTeamNotExist)(nil)
  222. type ErrTeamNotExist struct {
  223. args map[string]interface{}
  224. }
  225. func IsErrTeamNotExist(err error) bool {
  226. _, ok := err.(ErrTeamNotExist)
  227. return ok
  228. }
  229. func (err ErrTeamNotExist) Error() string {
  230. return fmt.Sprintf("team does not exist: %v", err.args)
  231. }
  232. func (ErrTeamNotExist) NotFound() bool {
  233. return true
  234. }
  235. func getTeamOfOrgByName(e Engine, orgID int64, name string) (*Team, error) {
  236. t := &Team{
  237. OrgID: orgID,
  238. LowerName: strings.ToLower(name),
  239. }
  240. has, err := e.Get(t)
  241. if err != nil {
  242. return nil, err
  243. } else if !has {
  244. return nil, ErrTeamNotExist{args: map[string]interface{}{"orgID": orgID, "name": name}}
  245. }
  246. return t, nil
  247. }
  248. // GetTeamOfOrgByName returns team by given team name and organization.
  249. func GetTeamOfOrgByName(orgID int64, name string) (*Team, error) {
  250. return getTeamOfOrgByName(x, orgID, name)
  251. }
  252. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  253. t := new(Team)
  254. has, err := e.ID(teamID).Get(t)
  255. if err != nil {
  256. return nil, err
  257. } else if !has {
  258. return nil, ErrTeamNotExist{args: map[string]interface{}{"teamID": teamID}}
  259. }
  260. return t, nil
  261. }
  262. // GetTeamByID returns team by given ID.
  263. func GetTeamByID(teamID int64) (*Team, error) {
  264. return getTeamByID(x, teamID)
  265. }
  266. func getTeamsByOrgID(e Engine, orgID int64) ([]*Team, error) {
  267. teams := make([]*Team, 0, 3)
  268. return teams, e.Where("org_id = ?", orgID).Find(&teams)
  269. }
  270. // GetTeamsByOrgID returns all teams belong to given organization.
  271. func GetTeamsByOrgID(orgID int64) ([]*Team, error) {
  272. return getTeamsByOrgID(x, orgID)
  273. }
  274. // UpdateTeam updates information of team.
  275. func UpdateTeam(t *Team, authChanged bool) (err error) {
  276. if len(t.Name) == 0 {
  277. return errors.New("empty team name")
  278. }
  279. if len(t.Description) > 255 {
  280. t.Description = t.Description[:255]
  281. }
  282. sess := x.NewSession()
  283. defer sess.Close()
  284. if err = sess.Begin(); err != nil {
  285. return err
  286. }
  287. t.LowerName = strings.ToLower(t.Name)
  288. existingTeam := new(Team)
  289. has, err := x.Where("org_id=?", t.OrgID).And("lower_name=?", t.LowerName).And("id!=?", t.ID).Get(&existingTeam)
  290. if err != nil {
  291. return err
  292. } else if has {
  293. return ErrTeamAlreadyExist{existingTeam.ID, t.OrgID, t.LowerName}
  294. }
  295. if _, err = sess.ID(t.ID).AllCols().Update(t); err != nil {
  296. return fmt.Errorf("update: %v", err)
  297. }
  298. // Update access for team members if needed.
  299. if authChanged {
  300. if err = t.getRepositories(sess); err != nil {
  301. return fmt.Errorf("getRepositories:%v", err)
  302. }
  303. for _, repo := range t.Repos {
  304. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  305. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  306. }
  307. }
  308. }
  309. return sess.Commit()
  310. }
  311. // DeleteTeam deletes given team.
  312. // It's caller's responsibility to assign organization ID.
  313. func DeleteTeam(t *Team) error {
  314. if err := t.GetRepositories(); err != nil {
  315. return err
  316. }
  317. // Get organization.
  318. org, err := GetUserByID(t.OrgID)
  319. if err != nil {
  320. return err
  321. }
  322. sess := x.NewSession()
  323. defer sess.Close()
  324. if err = sess.Begin(); err != nil {
  325. return err
  326. }
  327. // Delete all accesses.
  328. for _, repo := range t.Repos {
  329. if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  330. return err
  331. }
  332. }
  333. // Delete team-user.
  334. if _, err = sess.Where("org_id=?", org.ID).Where("team_id=?", t.ID).Delete(new(TeamUser)); err != nil {
  335. return err
  336. }
  337. // Delete team.
  338. if _, err = sess.ID(t.ID).Delete(new(Team)); err != nil {
  339. return err
  340. }
  341. // Update organization number of teams.
  342. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  343. return err
  344. }
  345. return sess.Commit()
  346. }
  347. // ___________ ____ ___
  348. // \__ ___/___ _____ _____ | | \______ ___________
  349. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  350. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  351. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  352. // \/ \/ \/ \/ \/
  353. // TeamUser represents an team-user relation.
  354. type TeamUser struct {
  355. ID int64
  356. OrgID int64 `xorm:"INDEX"`
  357. TeamID int64 `xorm:"UNIQUE(s)"`
  358. UID int64 `xorm:"UNIQUE(s)"`
  359. }
  360. func isTeamMember(e Engine, orgID, teamID, uid int64) bool {
  361. has, _ := e.Where("org_id=?", orgID).And("team_id=?", teamID).And("uid=?", uid).Get(new(TeamUser))
  362. return has
  363. }
  364. // IsTeamMember returns true if given user is a member of team.
  365. func IsTeamMember(orgID, teamID, uid int64) bool {
  366. return isTeamMember(x, orgID, teamID, uid)
  367. }
  368. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  369. teamUsers := make([]*TeamUser, 0, 10)
  370. if err = e.Sql("SELECT `id`, `org_id`, `team_id`, `uid` FROM `team_user` WHERE team_id = ?", teamID).
  371. Find(&teamUsers); err != nil {
  372. return nil, fmt.Errorf("get team-users: %v", err)
  373. }
  374. members := make([]*User, 0, len(teamUsers))
  375. for i := range teamUsers {
  376. member := new(User)
  377. if _, err = e.ID(teamUsers[i].UID).Get(member); err != nil {
  378. return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].UID, err)
  379. }
  380. members = append(members, member)
  381. }
  382. return members, nil
  383. }
  384. // GetTeamMembers returns all members in given team of organization.
  385. func GetTeamMembers(teamID int64) ([]*User, error) {
  386. return getTeamMembers(x, teamID)
  387. }
  388. func getUserTeams(e Engine, orgID, userID int64) ([]*Team, error) {
  389. teamUsers := make([]*TeamUser, 0, 5)
  390. if err := e.Where("uid = ?", userID).And("org_id = ?", orgID).Find(&teamUsers); err != nil {
  391. return nil, err
  392. }
  393. teamIDs := make([]int64, len(teamUsers)+1)
  394. for i := range teamUsers {
  395. teamIDs[i] = teamUsers[i].TeamID
  396. }
  397. teamIDs[len(teamUsers)] = -1
  398. teams := make([]*Team, 0, len(teamIDs))
  399. return teams, e.Where("org_id = ?", orgID).In("id", teamIDs).Find(&teams)
  400. }
  401. // GetUserTeams returns all teams that user belongs to in given organization.
  402. func GetUserTeams(orgID, userID int64) ([]*Team, error) {
  403. return getUserTeams(x, orgID, userID)
  404. }
  405. // AddTeamMember adds new membership of given team to given organization,
  406. // the user will have membership to given organization automatically when needed.
  407. func AddTeamMember(orgID, teamID, userID int64) error {
  408. if IsTeamMember(orgID, teamID, userID) {
  409. return nil
  410. }
  411. if err := AddOrgUser(orgID, userID); err != nil {
  412. return err
  413. }
  414. // Get team and its repositories.
  415. t, err := GetTeamByID(teamID)
  416. if err != nil {
  417. return err
  418. }
  419. t.NumMembers++
  420. if err = t.GetRepositories(); err != nil {
  421. return err
  422. }
  423. sess := x.NewSession()
  424. defer sess.Close()
  425. if err = sess.Begin(); err != nil {
  426. return err
  427. }
  428. tu := &TeamUser{
  429. UID: userID,
  430. OrgID: orgID,
  431. TeamID: teamID,
  432. }
  433. if _, err = sess.Insert(tu); err != nil {
  434. return err
  435. } else if _, err = sess.ID(t.ID).Update(t); err != nil {
  436. return err
  437. }
  438. // Give access to team repositories.
  439. for _, repo := range t.Repos {
  440. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  441. return err
  442. }
  443. }
  444. // We make sure it exists before.
  445. ou := new(OrgUser)
  446. if _, err = sess.Where("uid = ?", userID).And("org_id = ?", orgID).Get(ou); err != nil {
  447. return err
  448. }
  449. ou.NumTeams++
  450. if t.IsOwnerTeam() {
  451. ou.IsOwner = true
  452. }
  453. if _, err = sess.ID(ou.ID).AllCols().Update(ou); err != nil {
  454. return err
  455. }
  456. return sess.Commit()
  457. }
  458. func removeTeamMember(e Engine, orgID, teamID, uid int64) error {
  459. if !isTeamMember(e, orgID, teamID, uid) {
  460. return nil
  461. }
  462. // Get team and its repositories.
  463. t, err := getTeamByID(e, teamID)
  464. if err != nil {
  465. return err
  466. }
  467. // Check if the user to delete is the last member in owner team.
  468. if t.IsOwnerTeam() && t.NumMembers == 1 {
  469. return ErrLastOrgOwner{UID: uid}
  470. }
  471. t.NumMembers--
  472. if err = t.getRepositories(e); err != nil {
  473. return err
  474. }
  475. // Get organization.
  476. org, err := getUserByID(e, orgID)
  477. if err != nil {
  478. return err
  479. }
  480. tu := &TeamUser{
  481. UID: uid,
  482. OrgID: orgID,
  483. TeamID: teamID,
  484. }
  485. if _, err := e.Delete(tu); err != nil {
  486. return err
  487. } else if _, err = e.ID(t.ID).AllCols().Update(t); err != nil {
  488. return err
  489. }
  490. // Delete access to team repositories.
  491. for _, repo := range t.Repos {
  492. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  493. return err
  494. }
  495. }
  496. // This must exist.
  497. ou := new(OrgUser)
  498. _, err = e.Where("uid = ?", uid).And("org_id = ?", org.ID).Get(ou)
  499. if err != nil {
  500. return err
  501. }
  502. ou.NumTeams--
  503. if t.IsOwnerTeam() {
  504. ou.IsOwner = false
  505. }
  506. if _, err = e.ID(ou.ID).AllCols().Update(ou); err != nil {
  507. return err
  508. }
  509. return nil
  510. }
  511. // RemoveTeamMember removes member from given team of given organization.
  512. func RemoveTeamMember(orgID, teamID, uid int64) error {
  513. sess := x.NewSession()
  514. defer sess.Close()
  515. if err := sess.Begin(); err != nil {
  516. return err
  517. }
  518. if err := removeTeamMember(sess, orgID, teamID, uid); err != nil {
  519. return err
  520. }
  521. return sess.Commit()
  522. }
  523. // ___________ __________
  524. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  525. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  526. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  527. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  528. // \/ \/ \/ \/ \/|__|
  529. // TeamRepo represents an team-repository relation.
  530. type TeamRepo struct {
  531. ID int64
  532. OrgID int64 `xorm:"INDEX"`
  533. TeamID int64 `xorm:"UNIQUE(s)"`
  534. RepoID int64 `xorm:"UNIQUE(s)"`
  535. }
  536. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  537. has, _ := e.Where("org_id = ?", orgID).And("team_id = ?", teamID).And("repo_id = ?", repoID).Get(new(TeamRepo))
  538. return has
  539. }
  540. // HasTeamRepo returns true if given team has access to the repository of the organization.
  541. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  542. return hasTeamRepo(x, orgID, teamID, repoID)
  543. }
  544. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  545. _, err := e.InsertOne(&TeamRepo{
  546. OrgID: orgID,
  547. TeamID: teamID,
  548. RepoID: repoID,
  549. })
  550. return err
  551. }
  552. // AddTeamRepo adds new repository relation to team.
  553. func AddTeamRepo(orgID, teamID, repoID int64) error {
  554. return addTeamRepo(x, orgID, teamID, repoID)
  555. }
  556. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  557. _, err := e.Delete(&TeamRepo{
  558. TeamID: teamID,
  559. RepoID: repoID,
  560. })
  561. return err
  562. }
  563. // RemoveTeamRepo deletes repository relation to team.
  564. func RemoveTeamRepo(teamID, repoID int64) error {
  565. return removeTeamRepo(x, teamID, repoID)
  566. }
  567. // GetTeamsHaveAccessToRepo returns all teams in an organization that have given access level to the repository.
  568. func GetTeamsHaveAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
  569. teams := make([]*Team, 0, 5)
  570. return teams, x.Where("team.authorize >= ?", mode).
  571. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  572. And("team_repo.org_id = ?", orgID).
  573. And("team_repo.repo_id = ?", repoID).
  574. Find(&teams)
  575. }