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.

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