You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1018 lines
24 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 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. "os"
  9. "strings"
  10. "github.com/go-xorm/xorm"
  11. )
  12. var (
  13. ErrOrgNotExist = errors.New("Organization does not exist")
  14. ErrTeamAlreadyExist = errors.New("Team already exist")
  15. ErrTeamNotExist = errors.New("Team does not exist")
  16. ErrTeamNameIllegal = errors.New("Team name contains illegal characters")
  17. )
  18. // IsOwnedBy returns true if given user is in the owner team.
  19. func (org *User) IsOwnedBy(uid int64) bool {
  20. return IsOrganizationOwner(org.Id, uid)
  21. }
  22. // IsOrgMember returns true if given user is member of organization.
  23. func (org *User) IsOrgMember(uid int64) bool {
  24. return org.IsOrganization() && IsOrganizationMember(org.Id, uid)
  25. }
  26. func (org *User) getTeam(e Engine, name string) (*Team, error) {
  27. return getTeam(e, org.Id, name)
  28. }
  29. // GetTeam returns named team of organization.
  30. func (org *User) GetTeam(name string) (*Team, error) {
  31. return org.getTeam(x, name)
  32. }
  33. func (org *User) getOwnerTeam(e Engine) (*Team, error) {
  34. return org.getTeam(e, OWNER_TEAM)
  35. }
  36. // GetOwnerTeam returns owner team of organization.
  37. func (org *User) GetOwnerTeam() (*Team, error) {
  38. return org.getOwnerTeam(x)
  39. }
  40. func (org *User) getTeams(e Engine) error {
  41. return e.Where("org_id=?", org.Id).Find(&org.Teams)
  42. }
  43. // GetTeams returns all teams that belong to organization.
  44. func (org *User) GetTeams() error {
  45. return org.getTeams(x)
  46. }
  47. // GetMembers returns all members of organization.
  48. func (org *User) GetMembers() error {
  49. ous, err := GetOrgUsersByOrgId(org.Id)
  50. if err != nil {
  51. return err
  52. }
  53. org.Members = make([]*User, len(ous))
  54. for i, ou := range ous {
  55. org.Members[i], err = GetUserByID(ou.Uid)
  56. if err != nil {
  57. return err
  58. }
  59. }
  60. return nil
  61. }
  62. // AddMember adds new member to organization.
  63. func (org *User) AddMember(uid int64) error {
  64. return AddOrgUser(org.Id, uid)
  65. }
  66. // RemoveMember removes member from organization.
  67. func (org *User) RemoveMember(uid int64) error {
  68. return RemoveOrgUser(org.Id, uid)
  69. }
  70. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  71. return removeOrgRepo(e, org.Id, repoID)
  72. }
  73. // RemoveOrgRepo removes all team-repository relations of organization.
  74. func (org *User) RemoveOrgRepo(repoID int64) error {
  75. return org.removeOrgRepo(x, repoID)
  76. }
  77. // CreateOrganization creates record of a new organization.
  78. func CreateOrganization(org, owner *User) (err error) {
  79. if err = IsUsableName(org.Name); err != nil {
  80. return err
  81. }
  82. isExist, err := IsUserExist(0, org.Name)
  83. if err != nil {
  84. return err
  85. } else if isExist {
  86. return ErrUserAlreadyExist{org.Name}
  87. }
  88. org.LowerName = strings.ToLower(org.Name)
  89. org.FullName = org.Name
  90. org.UseCustomAvatar = true
  91. org.NumTeams = 1
  92. org.NumMembers = 1
  93. sess := x.NewSession()
  94. defer sessionRelease(sess)
  95. if err = sess.Begin(); err != nil {
  96. return err
  97. }
  98. if _, err = sess.Insert(org); err != nil {
  99. return fmt.Errorf("insert organization: %v", err)
  100. }
  101. org.GenerateRandomAvatar()
  102. // Add initial creator to organization and owner team.
  103. if _, err = sess.Insert(&OrgUser{
  104. Uid: owner.Id,
  105. OrgID: org.Id,
  106. IsOwner: true,
  107. NumTeams: 1,
  108. }); err != nil {
  109. return fmt.Errorf("insert org-user relation: %v", err)
  110. }
  111. // Create default owner team.
  112. t := &Team{
  113. OrgID: org.Id,
  114. LowerName: strings.ToLower(OWNER_TEAM),
  115. Name: OWNER_TEAM,
  116. Authorize: ACCESS_MODE_OWNER,
  117. NumMembers: 1,
  118. }
  119. if _, err = sess.Insert(t); err != nil {
  120. return fmt.Errorf("insert owner team: %v", err)
  121. }
  122. if _, err = sess.Insert(&TeamUser{
  123. Uid: owner.Id,
  124. OrgID: org.Id,
  125. TeamID: t.ID,
  126. }); err != nil {
  127. return fmt.Errorf("insert team-user relation: %v", err)
  128. }
  129. if err = os.MkdirAll(UserPath(org.Name), os.ModePerm); err != nil {
  130. return fmt.Errorf("create directory: %v", err)
  131. }
  132. return sess.Commit()
  133. }
  134. // GetOrgByName returns organization by given name.
  135. func GetOrgByName(name string) (*User, error) {
  136. if len(name) == 0 {
  137. return nil, ErrOrgNotExist
  138. }
  139. u := &User{
  140. LowerName: strings.ToLower(name),
  141. Type: ORGANIZATION,
  142. }
  143. has, err := x.Get(u)
  144. if err != nil {
  145. return nil, err
  146. } else if !has {
  147. return nil, ErrOrgNotExist
  148. }
  149. return u, nil
  150. }
  151. // CountOrganizations returns number of organizations.
  152. func CountOrganizations() int64 {
  153. count, _ := x.Where("type=1").Count(new(User))
  154. return count
  155. }
  156. // GetOrganizations returns given number of organizations with offset.
  157. func GetOrganizations(num, offset int) ([]*User, error) {
  158. orgs := make([]*User, 0, num)
  159. err := x.Limit(num, offset).Where("type=1").Asc("id").Find(&orgs)
  160. return orgs, err
  161. }
  162. // DeleteOrganization completely and permanently deletes everything of organization.
  163. func DeleteOrganization(org *User) (err error) {
  164. if err := DeleteUser(org); err != nil {
  165. return err
  166. }
  167. sess := x.NewSession()
  168. defer sessionRelease(sess)
  169. if err = sess.Begin(); err != nil {
  170. return err
  171. }
  172. if err = deleteBeans(sess,
  173. &Team{OrgID: org.Id},
  174. &OrgUser{OrgID: org.Id},
  175. &TeamUser{OrgID: org.Id},
  176. ); err != nil {
  177. return fmt.Errorf("deleteBeans: %v", err)
  178. }
  179. if err = deleteUser(sess, org); err != nil {
  180. return fmt.Errorf("deleteUser: %v", err)
  181. }
  182. return sess.Commit()
  183. }
  184. // ________ ____ ___
  185. // \_____ \_______ ____ | | \______ ___________
  186. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  187. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  188. // \_______ /__| \___ /|______//____ >\___ >__|
  189. // \/ /_____/ \/ \/
  190. // OrgUser represents an organization-user relation.
  191. type OrgUser struct {
  192. ID int64 `xorm:"pk autoincr"`
  193. Uid int64 `xorm:"INDEX UNIQUE(s)"`
  194. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  195. IsPublic bool
  196. IsOwner bool
  197. NumTeams int
  198. }
  199. // IsOrganizationOwner returns true if given user is in the owner team.
  200. func IsOrganizationOwner(orgId, uid int64) bool {
  201. has, _ := x.Where("is_owner=?", true).And("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  202. return has
  203. }
  204. // IsOrganizationMember returns true if given user is member of organization.
  205. func IsOrganizationMember(orgId, uid int64) bool {
  206. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  207. return has
  208. }
  209. // IsPublicMembership returns true if given user public his/her membership.
  210. func IsPublicMembership(orgId, uid int64) bool {
  211. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
  212. return has
  213. }
  214. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  215. orgs := make([]*User, 0, 10)
  216. return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
  217. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  218. }
  219. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  220. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  221. sess := x.NewSession()
  222. return getOwnedOrgsByUserID(sess, userID)
  223. }
  224. // GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
  225. // given user ID and descring order by given condition.
  226. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  227. sess := x.NewSession()
  228. return getOwnedOrgsByUserID(sess.Desc(desc), userID)
  229. }
  230. // GetOrgUsersByUserId returns all organization-user relations by user ID.
  231. func GetOrgUsersByUserId(uid int64) ([]*OrgUser, error) {
  232. ous := make([]*OrgUser, 0, 10)
  233. err := x.Where("uid=?", uid).Find(&ous)
  234. return ous, err
  235. }
  236. // GetOrgUsersByOrgId returns all organization-user relations by organization ID.
  237. func GetOrgUsersByOrgId(orgId int64) ([]*OrgUser, error) {
  238. ous := make([]*OrgUser, 0, 10)
  239. err := x.Where("org_id=?", orgId).Find(&ous)
  240. return ous, err
  241. }
  242. // ChangeOrgUserStatus changes public or private membership status.
  243. func ChangeOrgUserStatus(orgId, uid int64, public bool) error {
  244. ou := new(OrgUser)
  245. has, err := x.Where("uid=?", uid).And("org_id=?", orgId).Get(ou)
  246. if err != nil {
  247. return err
  248. } else if !has {
  249. return nil
  250. }
  251. ou.IsPublic = public
  252. _, err = x.Id(ou.ID).AllCols().Update(ou)
  253. return err
  254. }
  255. // AddOrgUser adds new user to given organization.
  256. func AddOrgUser(orgId, uid int64) error {
  257. if IsOrganizationMember(orgId, uid) {
  258. return nil
  259. }
  260. sess := x.NewSession()
  261. defer sess.Close()
  262. if err := sess.Begin(); err != nil {
  263. return err
  264. }
  265. ou := &OrgUser{
  266. Uid: uid,
  267. OrgID: orgId,
  268. }
  269. if _, err := sess.Insert(ou); err != nil {
  270. sess.Rollback()
  271. return err
  272. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgId); err != nil {
  273. sess.Rollback()
  274. return err
  275. }
  276. return sess.Commit()
  277. }
  278. // RemoveOrgUser removes user from given organization.
  279. func RemoveOrgUser(orgId, uid int64) error {
  280. ou := new(OrgUser)
  281. has, err := x.Where("uid=?", uid).And("org_id=?", orgId).Get(ou)
  282. if err != nil {
  283. return fmt.Errorf("get org-user: %v", err)
  284. } else if !has {
  285. return nil
  286. }
  287. u, err := GetUserByID(uid)
  288. if err != nil {
  289. return fmt.Errorf("GetUserById: %v", err)
  290. }
  291. org, err := GetUserByID(orgId)
  292. if err != nil {
  293. return fmt.Errorf("get organization: %v", err)
  294. } else if err = org.GetRepositories(); err != nil {
  295. return fmt.Errorf("GetRepositories: %v", err)
  296. }
  297. // Check if the user to delete is the last member in owner team.
  298. if IsOrganizationOwner(orgId, uid) {
  299. t, err := org.GetOwnerTeam()
  300. if err != nil {
  301. return err
  302. }
  303. if t.NumMembers == 1 {
  304. return ErrLastOrgOwner{UID: uid}
  305. }
  306. }
  307. sess := x.NewSession()
  308. defer sessionRelease(sess)
  309. if err := sess.Begin(); err != nil {
  310. return err
  311. }
  312. if _, err := sess.Id(ou.ID).Delete(ou); err != nil {
  313. return err
  314. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgId); err != nil {
  315. return err
  316. }
  317. // Delete all repository accesses.
  318. access := &Access{UserID: u.Id}
  319. for _, repo := range org.Repos {
  320. access.RepoID = repo.ID
  321. if _, err = sess.Delete(access); err != nil {
  322. return err
  323. } else if err = watchRepo(sess, u.Id, repo.ID, false); err != nil {
  324. return err
  325. }
  326. }
  327. // Delete member in his/her teams.
  328. teams, err := getUserTeams(sess, org.Id, u.Id)
  329. if err != nil {
  330. return err
  331. }
  332. for _, t := range teams {
  333. if err = removeTeamMember(sess, org.Id, t.ID, u.Id); err != nil {
  334. return err
  335. }
  336. }
  337. return sess.Commit()
  338. }
  339. // ___________
  340. // \__ ___/___ _____ _____
  341. // | |_/ __ \\__ \ / \
  342. // | |\ ___/ / __ \| Y Y \
  343. // |____| \___ >____ /__|_| /
  344. // \/ \/ \/
  345. const OWNER_TEAM = "Owners"
  346. // Team represents a organization team.
  347. type Team struct {
  348. ID int64 `xorm:"pk autoincr"`
  349. OrgID int64 `xorm:"INDEX"`
  350. LowerName string
  351. Name string
  352. Description string
  353. Authorize AccessMode
  354. Repos []*Repository `xorm:"-"`
  355. Members []*User `xorm:"-"`
  356. NumRepos int
  357. NumMembers int
  358. }
  359. // IsOwnerTeam returns true if team is owner team.
  360. func (t *Team) IsOwnerTeam() bool {
  361. return t.Name == OWNER_TEAM
  362. }
  363. // IsTeamMember returns true if given user is a member of team.
  364. func (t *Team) IsMember(uid int64) bool {
  365. return IsTeamMember(t.OrgID, t.ID, uid)
  366. }
  367. func (t *Team) getRepositories(e Engine) (err error) {
  368. teamRepos := make([]*TeamRepo, 0, t.NumRepos)
  369. if err = x.Where("team_id=?", t.ID).Find(&teamRepos); err != nil {
  370. return fmt.Errorf("get team-repos: %v", err)
  371. }
  372. t.Repos = make([]*Repository, 0, len(teamRepos))
  373. for i := range teamRepos {
  374. repo, err := getRepositoryByID(e, teamRepos[i].RepoID)
  375. if err != nil {
  376. return fmt.Errorf("getRepositoryById(%d): %v", teamRepos[i].RepoID, err)
  377. }
  378. t.Repos = append(t.Repos, repo)
  379. }
  380. return nil
  381. }
  382. // GetRepositories returns all repositories in team of organization.
  383. func (t *Team) GetRepositories() error {
  384. return t.getRepositories(x)
  385. }
  386. func (t *Team) getMembers(e Engine) (err error) {
  387. t.Members, err = getTeamMembers(e, t.ID)
  388. return err
  389. }
  390. // GetMembers returns all members in team of organization.
  391. func (t *Team) GetMembers() (err error) {
  392. return t.getMembers(x)
  393. }
  394. // AddMember adds new member to team of organization.
  395. func (t *Team) AddMember(uid int64) error {
  396. return AddTeamMember(t.OrgID, t.ID, uid)
  397. }
  398. // RemoveMember removes member from team of organization.
  399. func (t *Team) RemoveMember(uid int64) error {
  400. return RemoveTeamMember(t.OrgID, t.ID, uid)
  401. }
  402. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  403. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  404. }
  405. // HasRepository returns true if given repository belong to team.
  406. func (t *Team) HasRepository(repoID int64) bool {
  407. return t.hasRepository(x, repoID)
  408. }
  409. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  410. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  411. return err
  412. }
  413. t.NumRepos++
  414. if _, err = e.Id(t.ID).AllCols().Update(t); err != nil {
  415. return fmt.Errorf("update team: %v", err)
  416. }
  417. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  418. return fmt.Errorf("recalculateAccesses: %v", err)
  419. }
  420. if err = t.getMembers(e); err != nil {
  421. return fmt.Errorf("getMembers: %v", err)
  422. }
  423. for _, u := range t.Members {
  424. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  425. return fmt.Errorf("watchRepo: %v", err)
  426. }
  427. }
  428. return nil
  429. }
  430. // AddRepository adds new repository to team of organization.
  431. func (t *Team) AddRepository(repo *Repository) (err error) {
  432. if repo.OwnerID != t.OrgID {
  433. return errors.New("Repository does not belong to organization")
  434. } else if t.HasRepository(repo.ID) {
  435. return nil
  436. }
  437. sess := x.NewSession()
  438. defer sessionRelease(sess)
  439. if err = sess.Begin(); err != nil {
  440. return err
  441. }
  442. if err = t.addRepository(sess, repo); err != nil {
  443. return err
  444. }
  445. return sess.Commit()
  446. }
  447. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  448. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  449. return err
  450. }
  451. t.NumRepos--
  452. if _, err = e.Id(t.ID).AllCols().Update(t); err != nil {
  453. return err
  454. }
  455. // Don't need to recalculate when delete a repository from organization.
  456. if recalculate {
  457. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  458. return err
  459. }
  460. }
  461. if err = t.getMembers(e); err != nil {
  462. return fmt.Errorf("get team members: %v", err)
  463. }
  464. for _, u := range t.Members {
  465. has, err := hasAccess(e, u, repo, ACCESS_MODE_READ)
  466. if err != nil {
  467. return err
  468. } else if has {
  469. continue
  470. }
  471. if err = watchRepo(e, u.Id, repo.ID, false); err != nil {
  472. return err
  473. }
  474. }
  475. return nil
  476. }
  477. // RemoveRepository removes repository from team of organization.
  478. func (t *Team) RemoveRepository(repoID int64) error {
  479. if !t.HasRepository(repoID) {
  480. return nil
  481. }
  482. repo, err := GetRepositoryByID(repoID)
  483. if err != nil {
  484. return err
  485. }
  486. sess := x.NewSession()
  487. defer sessionRelease(sess)
  488. if err = sess.Begin(); err != nil {
  489. return err
  490. }
  491. if err = t.removeRepository(sess, repo, true); err != nil {
  492. return err
  493. }
  494. return sess.Commit()
  495. }
  496. // NewTeam creates a record of new team.
  497. // It's caller's responsibility to assign organization ID.
  498. func NewTeam(t *Team) (err error) {
  499. if err = IsUsableName(t.Name); err != nil {
  500. return err
  501. }
  502. has, err := x.Id(t.OrgID).Get(new(User))
  503. if err != nil {
  504. return err
  505. } else if !has {
  506. return ErrOrgNotExist
  507. }
  508. t.LowerName = strings.ToLower(t.Name)
  509. has, err = x.Where("org_id=?", t.OrgID).And("lower_name=?", t.LowerName).Get(new(Team))
  510. if err != nil {
  511. return err
  512. } else if has {
  513. return ErrTeamAlreadyExist
  514. }
  515. sess := x.NewSession()
  516. defer sess.Close()
  517. if err = sess.Begin(); err != nil {
  518. return err
  519. }
  520. if _, err = sess.Insert(t); err != nil {
  521. sess.Rollback()
  522. return err
  523. }
  524. // Update organization number of teams.
  525. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  526. sess.Rollback()
  527. return err
  528. }
  529. return sess.Commit()
  530. }
  531. func getTeam(e Engine, orgId int64, name string) (*Team, error) {
  532. t := &Team{
  533. OrgID: orgId,
  534. LowerName: strings.ToLower(name),
  535. }
  536. has, err := e.Get(t)
  537. if err != nil {
  538. return nil, err
  539. } else if !has {
  540. return nil, ErrTeamNotExist
  541. }
  542. return t, nil
  543. }
  544. // GetTeam returns team by given team name and organization.
  545. func GetTeam(orgId int64, name string) (*Team, error) {
  546. return getTeam(x, orgId, name)
  547. }
  548. func getTeamById(e Engine, teamId int64) (*Team, error) {
  549. t := new(Team)
  550. has, err := e.Id(teamId).Get(t)
  551. if err != nil {
  552. return nil, err
  553. } else if !has {
  554. return nil, ErrTeamNotExist
  555. }
  556. return t, nil
  557. }
  558. // GetTeamById returns team by given ID.
  559. func GetTeamById(teamId int64) (*Team, error) {
  560. return getTeamById(x, teamId)
  561. }
  562. // UpdateTeam updates information of team.
  563. func UpdateTeam(t *Team, authChanged bool) (err error) {
  564. if err = IsUsableName(t.Name); err != nil {
  565. return err
  566. }
  567. if len(t.Description) > 255 {
  568. t.Description = t.Description[:255]
  569. }
  570. sess := x.NewSession()
  571. defer sessionRelease(sess)
  572. if err = sess.Begin(); err != nil {
  573. return err
  574. }
  575. t.LowerName = strings.ToLower(t.Name)
  576. if _, err = sess.Id(t.ID).AllCols().Update(t); err != nil {
  577. return fmt.Errorf("update: %v", err)
  578. }
  579. // Update access for team members if needed.
  580. if authChanged {
  581. if err = t.getRepositories(sess); err != nil {
  582. return fmt.Errorf("getRepositories:%v", err)
  583. }
  584. for _, repo := range t.Repos {
  585. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  586. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  587. }
  588. }
  589. }
  590. return sess.Commit()
  591. }
  592. // DeleteTeam deletes given team.
  593. // It's caller's responsibility to assign organization ID.
  594. func DeleteTeam(t *Team) error {
  595. if err := t.GetRepositories(); err != nil {
  596. return err
  597. }
  598. // Get organization.
  599. org, err := GetUserByID(t.OrgID)
  600. if err != nil {
  601. return err
  602. }
  603. sess := x.NewSession()
  604. defer sessionRelease(sess)
  605. if err = sess.Begin(); err != nil {
  606. return err
  607. }
  608. // Delete all accesses.
  609. for _, repo := range t.Repos {
  610. if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  611. return err
  612. }
  613. }
  614. // Delete team-user.
  615. if _, err = sess.Where("org_id=?", org.Id).Where("team_id=?", t.ID).Delete(new(TeamUser)); err != nil {
  616. return err
  617. }
  618. // Delete team.
  619. if _, err = sess.Id(t.ID).Delete(new(Team)); err != nil {
  620. return err
  621. }
  622. // Update organization number of teams.
  623. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  624. return err
  625. }
  626. return sess.Commit()
  627. }
  628. // ___________ ____ ___
  629. // \__ ___/___ _____ _____ | | \______ ___________
  630. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  631. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  632. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  633. // \/ \/ \/ \/ \/
  634. // TeamUser represents an team-user relation.
  635. type TeamUser struct {
  636. ID int64 `xorm:"pk autoincr"`
  637. OrgID int64 `xorm:"INDEX"`
  638. TeamID int64 `xorm:"UNIQUE(s)"`
  639. Uid int64 `xorm:"UNIQUE(s)"`
  640. }
  641. func isTeamMember(e Engine, orgID, teamID, uid int64) bool {
  642. has, _ := e.Where("org_id=?", orgID).And("team_id=?", teamID).And("uid=?", uid).Get(new(TeamUser))
  643. return has
  644. }
  645. // IsTeamMember returns true if given user is a member of team.
  646. func IsTeamMember(orgID, teamID, uid int64) bool {
  647. return isTeamMember(x, orgID, teamID, uid)
  648. }
  649. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  650. teamUsers := make([]*TeamUser, 0, 10)
  651. if err = e.Where("team_id=?", teamID).Find(&teamUsers); err != nil {
  652. return nil, fmt.Errorf("get team-users: %v", err)
  653. }
  654. members := make([]*User, 0, len(teamUsers))
  655. for i := range teamUsers {
  656. member := new(User)
  657. if _, err = e.Id(teamUsers[i].Uid).Get(member); err != nil {
  658. return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].Uid, err)
  659. }
  660. members = append(members, member)
  661. }
  662. return members, nil
  663. }
  664. // GetTeamMembers returns all members in given team of organization.
  665. func GetTeamMembers(teamID int64) ([]*User, error) {
  666. return getTeamMembers(x, teamID)
  667. }
  668. func getUserTeams(e Engine, orgId, uid int64) ([]*Team, error) {
  669. tus := make([]*TeamUser, 0, 5)
  670. if err := e.Where("uid=?", uid).And("org_id=?", orgId).Find(&tus); err != nil {
  671. return nil, err
  672. }
  673. ts := make([]*Team, len(tus))
  674. for i, tu := range tus {
  675. t := new(Team)
  676. has, err := e.Id(tu.TeamID).Get(t)
  677. if err != nil {
  678. return nil, err
  679. } else if !has {
  680. return nil, ErrTeamNotExist
  681. }
  682. ts[i] = t
  683. }
  684. return ts, nil
  685. }
  686. // GetUserTeams returns all teams that user belongs to in given organization.
  687. func GetUserTeams(orgId, uid int64) ([]*Team, error) {
  688. return getUserTeams(x, orgId, uid)
  689. }
  690. // AddTeamMember adds new member to given team of given organization.
  691. func AddTeamMember(orgId, teamId, uid int64) error {
  692. if IsTeamMember(orgId, teamId, uid) {
  693. return nil
  694. }
  695. if err := AddOrgUser(orgId, uid); err != nil {
  696. return err
  697. }
  698. // Get team and its repositories.
  699. t, err := GetTeamById(teamId)
  700. if err != nil {
  701. return err
  702. }
  703. t.NumMembers++
  704. if err = t.GetRepositories(); err != nil {
  705. return err
  706. }
  707. sess := x.NewSession()
  708. defer sessionRelease(sess)
  709. if err = sess.Begin(); err != nil {
  710. return err
  711. }
  712. tu := &TeamUser{
  713. Uid: uid,
  714. OrgID: orgId,
  715. TeamID: teamId,
  716. }
  717. if _, err = sess.Insert(tu); err != nil {
  718. return err
  719. } else if _, err = sess.Id(t.ID).Update(t); err != nil {
  720. return err
  721. }
  722. // Give access to team repositories.
  723. for _, repo := range t.Repos {
  724. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  725. return err
  726. }
  727. }
  728. // We make sure it exists before.
  729. ou := new(OrgUser)
  730. if _, err = sess.Where("uid=?", uid).And("org_id=?", orgId).Get(ou); err != nil {
  731. return err
  732. }
  733. ou.NumTeams++
  734. if t.IsOwnerTeam() {
  735. ou.IsOwner = true
  736. }
  737. if _, err = sess.Id(ou.ID).AllCols().Update(ou); err != nil {
  738. return err
  739. }
  740. return sess.Commit()
  741. }
  742. func removeTeamMember(e Engine, orgId, teamId, uid int64) error {
  743. if !isTeamMember(e, orgId, teamId, uid) {
  744. return nil
  745. }
  746. // Get team and its repositories.
  747. t, err := getTeamById(e, teamId)
  748. if err != nil {
  749. return err
  750. }
  751. // Check if the user to delete is the last member in owner team.
  752. if t.IsOwnerTeam() && t.NumMembers == 1 {
  753. return ErrLastOrgOwner{UID: uid}
  754. }
  755. t.NumMembers--
  756. if err = t.getRepositories(e); err != nil {
  757. return err
  758. }
  759. // Get organization.
  760. org, err := getUserByID(e, orgId)
  761. if err != nil {
  762. return err
  763. }
  764. tu := &TeamUser{
  765. Uid: uid,
  766. OrgID: orgId,
  767. TeamID: teamId,
  768. }
  769. if _, err := e.Delete(tu); err != nil {
  770. return err
  771. } else if _, err = e.Id(t.ID).AllCols().Update(t); err != nil {
  772. return err
  773. }
  774. // Delete access to team repositories.
  775. for _, repo := range t.Repos {
  776. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  777. return err
  778. }
  779. }
  780. // This must exist.
  781. ou := new(OrgUser)
  782. _, err = e.Where("uid=?", uid).And("org_id=?", org.Id).Get(ou)
  783. if err != nil {
  784. return err
  785. }
  786. ou.NumTeams--
  787. if t.IsOwnerTeam() {
  788. ou.IsOwner = false
  789. }
  790. if _, err = e.Id(ou.ID).AllCols().Update(ou); err != nil {
  791. return err
  792. }
  793. return nil
  794. }
  795. // RemoveTeamMember removes member from given team of given organization.
  796. func RemoveTeamMember(orgId, teamId, uid int64) error {
  797. sess := x.NewSession()
  798. defer sessionRelease(sess)
  799. if err := sess.Begin(); err != nil {
  800. return err
  801. }
  802. if err := removeTeamMember(sess, orgId, teamId, uid); err != nil {
  803. return err
  804. }
  805. return sess.Commit()
  806. }
  807. // ___________ __________
  808. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  809. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  810. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  811. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  812. // \/ \/ \/ \/ \/|__|
  813. // TeamRepo represents an team-repository relation.
  814. type TeamRepo struct {
  815. ID int64 `xorm:"pk autoincr"`
  816. OrgID int64 `xorm:"INDEX"`
  817. TeamID int64 `xorm:"UNIQUE(s)"`
  818. RepoID int64 `xorm:"UNIQUE(s)"`
  819. }
  820. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  821. has, _ := e.Where("org_id=?", orgID).And("team_id=?", teamID).And("repo_id=?", repoID).Get(new(TeamRepo))
  822. return has
  823. }
  824. // HasTeamRepo returns true if given repository belongs to team.
  825. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  826. return hasTeamRepo(x, orgID, teamID, repoID)
  827. }
  828. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  829. _, err := e.InsertOne(&TeamRepo{
  830. OrgID: orgID,
  831. TeamID: teamID,
  832. RepoID: repoID,
  833. })
  834. return err
  835. }
  836. // AddTeamRepo adds new repository relation to team.
  837. func AddTeamRepo(orgID, teamID, repoID int64) error {
  838. return addTeamRepo(x, orgID, teamID, repoID)
  839. }
  840. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  841. _, err := e.Delete(&TeamRepo{
  842. TeamID: teamID,
  843. RepoID: repoID,
  844. })
  845. return err
  846. }
  847. // RemoveTeamRepo deletes repository relation to team.
  848. func RemoveTeamRepo(teamID, repoID int64) error {
  849. return removeTeamRepo(x, teamID, repoID)
  850. }
  851. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  852. _, err := e.Delete(&TeamRepo{
  853. OrgID: orgID,
  854. RepoID: repoID,
  855. })
  856. return err
  857. }
  858. // RemoveOrgRepo removes all team-repository relations of given organization.
  859. func RemoveOrgRepo(orgID, repoID int64) error {
  860. return removeOrgRepo(x, orgID, repoID)
  861. }