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.

678 lines
17 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
8 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/builder"
  12. "github.com/go-xorm/xorm"
  13. )
  14. var (
  15. // ErrOrgNotExist organization does not exist
  16. ErrOrgNotExist = errors.New("Organization does not exist")
  17. // ErrTeamNotExist team does not exist
  18. ErrTeamNotExist = errors.New("Team does not exist")
  19. )
  20. // IsOwnedBy returns true if given user is in the owner team.
  21. func (org *User) IsOwnedBy(uid int64) bool {
  22. return IsOrganizationOwner(org.ID, uid)
  23. }
  24. // IsOrgMember returns true if given user is member of organization.
  25. func (org *User) IsOrgMember(uid int64) bool {
  26. return org.IsOrganization() && IsOrganizationMember(org.ID, uid)
  27. }
  28. func (org *User) getTeam(e Engine, name string) (*Team, error) {
  29. return getTeam(e, org.ID, name)
  30. }
  31. // GetTeam returns named team of organization.
  32. func (org *User) GetTeam(name string) (*Team, error) {
  33. return org.getTeam(x, name)
  34. }
  35. func (org *User) getOwnerTeam(e Engine) (*Team, error) {
  36. return org.getTeam(e, ownerTeamName)
  37. }
  38. // GetOwnerTeam returns owner team of organization.
  39. func (org *User) GetOwnerTeam() (*Team, error) {
  40. return org.getOwnerTeam(x)
  41. }
  42. func (org *User) getTeams(e Engine) error {
  43. return e.
  44. Where("org_id=?", org.ID).
  45. OrderBy("CASE WHEN name LIKE '" + ownerTeamName + "' THEN '' ELSE name END").
  46. Find(&org.Teams)
  47. }
  48. // GetTeams returns all teams that belong to organization.
  49. func (org *User) GetTeams() error {
  50. return org.getTeams(x)
  51. }
  52. // GetMembers returns all members of organization.
  53. func (org *User) GetMembers() error {
  54. ous, err := GetOrgUsersByOrgID(org.ID)
  55. if err != nil {
  56. return err
  57. }
  58. var ids = make([]int64, len(ous))
  59. for i, ou := range ous {
  60. ids[i] = ou.UID
  61. }
  62. org.Members, err = GetUsersByIDs(ids)
  63. return err
  64. }
  65. // AddMember adds new member to organization.
  66. func (org *User) AddMember(uid int64) error {
  67. return AddOrgUser(org.ID, uid)
  68. }
  69. // RemoveMember removes member from organization.
  70. func (org *User) RemoveMember(uid int64) error {
  71. return RemoveOrgUser(org.ID, uid)
  72. }
  73. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  74. return removeOrgRepo(e, org.ID, repoID)
  75. }
  76. // RemoveOrgRepo removes all team-repository relations of organization.
  77. func (org *User) RemoveOrgRepo(repoID int64) error {
  78. return org.removeOrgRepo(x, repoID)
  79. }
  80. // CreateOrganization creates record of a new organization.
  81. func CreateOrganization(org, owner *User) (err error) {
  82. if !owner.CanCreateOrganization() {
  83. return ErrUserNotAllowedCreateOrg{}
  84. }
  85. if err = IsUsableUsername(org.Name); err != nil {
  86. return err
  87. }
  88. isExist, err := IsUserExist(0, org.Name)
  89. if err != nil {
  90. return err
  91. } else if isExist {
  92. return ErrUserAlreadyExist{org.Name}
  93. }
  94. org.LowerName = strings.ToLower(org.Name)
  95. if org.Rands, err = GetUserSalt(); err != nil {
  96. return err
  97. }
  98. if org.Salt, err = GetUserSalt(); err != nil {
  99. return err
  100. }
  101. org.UseCustomAvatar = true
  102. org.MaxRepoCreation = -1
  103. org.NumTeams = 1
  104. org.NumMembers = 1
  105. org.Type = UserTypeOrganization
  106. sess := x.NewSession()
  107. defer sessionRelease(sess)
  108. if err = sess.Begin(); err != nil {
  109. return err
  110. }
  111. if _, err = sess.Insert(org); err != nil {
  112. return fmt.Errorf("insert organization: %v", err)
  113. }
  114. org.GenerateRandomAvatar()
  115. // Add initial creator to organization and owner team.
  116. if _, err = sess.Insert(&OrgUser{
  117. UID: owner.ID,
  118. OrgID: org.ID,
  119. IsOwner: true,
  120. NumTeams: 1,
  121. }); err != nil {
  122. return fmt.Errorf("insert org-user relation: %v", err)
  123. }
  124. // Create default owner team.
  125. t := &Team{
  126. OrgID: org.ID,
  127. LowerName: strings.ToLower(ownerTeamName),
  128. Name: ownerTeamName,
  129. Authorize: AccessModeOwner,
  130. NumMembers: 1,
  131. }
  132. if _, err = sess.Insert(t); err != nil {
  133. return fmt.Errorf("insert owner team: %v", err)
  134. }
  135. if _, err = sess.Insert(&TeamUser{
  136. UID: owner.ID,
  137. OrgID: org.ID,
  138. TeamID: t.ID,
  139. }); err != nil {
  140. return fmt.Errorf("insert team-user relation: %v", err)
  141. }
  142. if err = os.MkdirAll(UserPath(org.Name), os.ModePerm); err != nil {
  143. return fmt.Errorf("create directory: %v", err)
  144. }
  145. return sess.Commit()
  146. }
  147. // GetOrgByName returns organization by given name.
  148. func GetOrgByName(name string) (*User, error) {
  149. if len(name) == 0 {
  150. return nil, ErrOrgNotExist
  151. }
  152. u := &User{
  153. LowerName: strings.ToLower(name),
  154. Type: UserTypeOrganization,
  155. }
  156. has, err := x.Get(u)
  157. if err != nil {
  158. return nil, err
  159. } else if !has {
  160. return nil, ErrOrgNotExist
  161. }
  162. return u, nil
  163. }
  164. // CountOrganizations returns number of organizations.
  165. func CountOrganizations() int64 {
  166. count, _ := x.
  167. Where("type=1").
  168. Count(new(User))
  169. return count
  170. }
  171. // Organizations returns number of organizations in given page.
  172. func Organizations(opts *SearchUserOptions) ([]*User, error) {
  173. orgs := make([]*User, 0, opts.PageSize)
  174. if len(opts.OrderBy) == 0 {
  175. opts.OrderBy = "name ASC"
  176. }
  177. sess := x.
  178. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  179. Where("type=1")
  180. return orgs, sess.
  181. OrderBy(opts.OrderBy).
  182. Find(&orgs)
  183. }
  184. // DeleteOrganization completely and permanently deletes everything of organization.
  185. func DeleteOrganization(org *User) (err error) {
  186. sess := x.NewSession()
  187. defer sess.Close()
  188. if err = sess.Begin(); err != nil {
  189. return err
  190. }
  191. if err = deleteOrg(sess, org); err != nil {
  192. if IsErrUserOwnRepos(err) {
  193. return err
  194. } else if err != nil {
  195. return fmt.Errorf("deleteOrg: %v", err)
  196. }
  197. }
  198. if err = sess.Commit(); err != nil {
  199. return err
  200. }
  201. return nil
  202. }
  203. func deleteOrg(e *xorm.Session, u *User) error {
  204. if !u.IsOrganization() {
  205. return fmt.Errorf("You can't delete none organization user: %s", u.Name)
  206. }
  207. // Check ownership of repository.
  208. count, err := getRepositoryCount(e, u)
  209. if err != nil {
  210. return fmt.Errorf("GetRepositoryCount: %v", err)
  211. } else if count > 0 {
  212. return ErrUserOwnRepos{UID: u.ID}
  213. }
  214. if err := deleteBeans(e,
  215. &Team{OrgID: u.ID},
  216. &OrgUser{OrgID: u.ID},
  217. &TeamUser{OrgID: u.ID},
  218. ); err != nil {
  219. return fmt.Errorf("deleteBeans: %v", err)
  220. }
  221. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  222. return fmt.Errorf("Delete: %v", err)
  223. }
  224. // FIXME: system notice
  225. // Note: There are something just cannot be roll back,
  226. // so just keep error logs of those operations.
  227. path := UserPath(u.Name)
  228. if err := os.RemoveAll(path); err != nil {
  229. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  230. }
  231. avatarPath := u.CustomAvatarPath()
  232. if com.IsExist(avatarPath) {
  233. if err := os.Remove(avatarPath); err != nil {
  234. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  235. }
  236. }
  237. return nil
  238. }
  239. // ________ ____ ___
  240. // \_____ \_______ ____ | | \______ ___________
  241. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  242. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  243. // \_______ /__| \___ /|______//____ >\___ >__|
  244. // \/ /_____/ \/ \/
  245. // OrgUser represents an organization-user relation.
  246. type OrgUser struct {
  247. ID int64 `xorm:"pk autoincr"`
  248. UID int64 `xorm:"INDEX UNIQUE(s)"`
  249. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  250. IsPublic bool `xorm:"INDEX"`
  251. IsOwner bool
  252. NumTeams int
  253. }
  254. // IsOrganizationOwner returns true if given user is in the owner team.
  255. func IsOrganizationOwner(orgID, uid int64) bool {
  256. has, _ := x.
  257. Where("is_owner=?", true).
  258. And("uid=?", uid).
  259. And("org_id=?", orgID).
  260. Get(new(OrgUser))
  261. return has
  262. }
  263. // IsOrganizationMember returns true if given user is member of organization.
  264. func IsOrganizationMember(orgID, uid int64) bool {
  265. has, _ := x.
  266. Where("uid=?", uid).
  267. And("org_id=?", orgID).
  268. Get(new(OrgUser))
  269. return has
  270. }
  271. // IsPublicMembership returns true if given user public his/her membership.
  272. func IsPublicMembership(orgID, uid int64) bool {
  273. has, _ := x.
  274. Where("uid=?", uid).
  275. And("org_id=?", orgID).
  276. And("is_public=?", true).
  277. Get(new(OrgUser))
  278. return has
  279. }
  280. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  281. orgs := make([]*User, 0, 10)
  282. if !showAll {
  283. sess.And("`org_user`.is_public=?", true)
  284. }
  285. return orgs, sess.
  286. And("`org_user`.uid=?", userID).
  287. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").
  288. Asc("`user`.name").
  289. Find(&orgs)
  290. }
  291. // GetOrgsByUserID returns a list of organizations that the given user ID
  292. // has joined.
  293. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  294. sess := x.NewSession()
  295. defer sess.Close()
  296. return getOrgsByUserID(sess, userID, showAll)
  297. }
  298. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  299. orgs := make([]*User, 0, 10)
  300. return orgs, sess.
  301. Where("`org_user`.uid=?", userID).
  302. And("`org_user`.is_owner=?", true).
  303. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").
  304. Asc("`user`.name").
  305. Find(&orgs)
  306. }
  307. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  308. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  309. sess := x.NewSession()
  310. defer sess.Close()
  311. return getOwnedOrgsByUserID(sess, userID)
  312. }
  313. // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
  314. // given user ID, ordered descending by the given condition.
  315. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  316. return getOwnedOrgsByUserID(x.Desc(desc), userID)
  317. }
  318. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  319. func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
  320. ous := make([]*OrgUser, 0, 10)
  321. sess := x.
  322. Join("LEFT", "user", "`org_user`.org_id=`user`.id").
  323. Where("`org_user`.uid=?", uid)
  324. if !all {
  325. // Only show public organizations
  326. sess.And("is_public=?", true)
  327. }
  328. err := sess.
  329. Asc("`user`.name").
  330. Find(&ous)
  331. return ous, err
  332. }
  333. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  334. func GetOrgUsersByOrgID(orgID int64) ([]*OrgUser, error) {
  335. ous := make([]*OrgUser, 0, 10)
  336. err := x.
  337. Where("org_id=?", orgID).
  338. Find(&ous)
  339. return ous, err
  340. }
  341. // ChangeOrgUserStatus changes public or private membership status.
  342. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  343. ou := new(OrgUser)
  344. has, err := x.
  345. Where("uid=?", uid).
  346. And("org_id=?", orgID).
  347. Get(ou)
  348. if err != nil {
  349. return err
  350. } else if !has {
  351. return nil
  352. }
  353. ou.IsPublic = public
  354. _, err = x.Id(ou.ID).AllCols().Update(ou)
  355. return err
  356. }
  357. // AddOrgUser adds new user to given organization.
  358. func AddOrgUser(orgID, uid int64) error {
  359. if IsOrganizationMember(orgID, uid) {
  360. return nil
  361. }
  362. sess := x.NewSession()
  363. defer sess.Close()
  364. if err := sess.Begin(); err != nil {
  365. return err
  366. }
  367. ou := &OrgUser{
  368. UID: uid,
  369. OrgID: orgID,
  370. }
  371. if _, err := sess.Insert(ou); err != nil {
  372. sess.Rollback()
  373. return err
  374. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  375. sess.Rollback()
  376. return err
  377. }
  378. return sess.Commit()
  379. }
  380. // RemoveOrgUser removes user from given organization.
  381. func RemoveOrgUser(orgID, userID int64) error {
  382. ou := new(OrgUser)
  383. has, err := x.
  384. Where("uid=?", userID).
  385. And("org_id=?", orgID).
  386. Get(ou)
  387. if err != nil {
  388. return fmt.Errorf("get org-user: %v", err)
  389. } else if !has {
  390. return nil
  391. }
  392. org, err := GetUserByID(orgID)
  393. if err != nil {
  394. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  395. }
  396. // Check if the user to delete is the last member in owner team.
  397. if IsOrganizationOwner(orgID, userID) {
  398. t, err := org.GetOwnerTeam()
  399. if err != nil {
  400. return err
  401. }
  402. if t.NumMembers == 1 {
  403. return ErrLastOrgOwner{UID: userID}
  404. }
  405. }
  406. sess := x.NewSession()
  407. defer sessionRelease(sess)
  408. if err := sess.Begin(); err != nil {
  409. return err
  410. }
  411. if _, err := sess.Id(ou.ID).Delete(ou); err != nil {
  412. return err
  413. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  414. return err
  415. }
  416. // Delete all repository accesses and unwatch them.
  417. env, err := org.AccessibleReposEnv(userID)
  418. if err != nil {
  419. return fmt.Errorf("AccessibleReposEnv: %v", err)
  420. }
  421. repoIDs, err := env.RepoIDs(1, org.NumRepos)
  422. if err != nil {
  423. return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err)
  424. }
  425. for _, repoID := range repoIDs {
  426. if err = watchRepo(sess, userID, repoID, false); err != nil {
  427. return err
  428. }
  429. }
  430. if len(repoIDs) > 0 {
  431. if _, err = sess.
  432. Where("user_id = ?", userID).
  433. In("repo_id", repoIDs).
  434. Delete(new(Access)); err != nil {
  435. return err
  436. }
  437. }
  438. // Delete member in his/her teams.
  439. teams, err := getUserTeams(sess, org.ID, userID)
  440. if err != nil {
  441. return err
  442. }
  443. for _, t := range teams {
  444. if err = removeTeamMember(sess, org.ID, t.ID, userID); err != nil {
  445. return err
  446. }
  447. }
  448. return sess.Commit()
  449. }
  450. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  451. teamRepos := make([]*TeamRepo, 0, 10)
  452. if err := e.Find(&teamRepos, &TeamRepo{OrgID: orgID, RepoID: repoID}); err != nil {
  453. return err
  454. }
  455. if len(teamRepos) == 0 {
  456. return nil
  457. }
  458. if _, err := e.Delete(&TeamRepo{
  459. OrgID: orgID,
  460. RepoID: repoID,
  461. }); err != nil {
  462. return err
  463. }
  464. teamIDs := make([]int64, len(teamRepos))
  465. for i, teamRepo := range teamRepos {
  466. teamIDs[i] = teamRepo.ID
  467. }
  468. _, err := x.Decr("num_repos").In("id", teamIDs).Update(new(Team))
  469. return err
  470. }
  471. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  472. teams := make([]*Team, 0, org.NumTeams)
  473. return teams, e.
  474. Where("`team_user`.org_id = ?", org.ID).
  475. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  476. Join("INNER", "user", "`user`.id=team_user.uid").
  477. And("`team_user`.uid = ?", userID).
  478. Asc("`user`.name").
  479. Cols(cols...).
  480. Find(&teams)
  481. }
  482. func (org *User) getUserTeamIDs(e Engine, userID int64) ([]int64, error) {
  483. teamIDs := make([]int64, 0, org.NumTeams)
  484. return teamIDs, e.
  485. Table("team").
  486. Cols("team.id").
  487. Where("`team_user`.org_id = ?", org.ID).
  488. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  489. And("`team_user`.uid = ?", userID).
  490. Find(&teamIDs)
  491. }
  492. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
  493. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  494. return org.getUserTeamIDs(x, userID)
  495. }
  496. // GetUserTeams returns all teams that belong to user,
  497. // and that the user has joined.
  498. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  499. return org.getUserTeams(x, userID)
  500. }
  501. // AccessibleReposEnvironment operations involving the repositories that are
  502. // accessible to a particular user
  503. type AccessibleReposEnvironment interface {
  504. CountRepos() (int64, error)
  505. RepoIDs(page, pageSize int) ([]int64, error)
  506. Repos(page, pageSize int) ([]*Repository, error)
  507. MirrorRepos() ([]*Repository, error)
  508. }
  509. type accessibleReposEnv struct {
  510. org *User
  511. userID int64
  512. teamIDs []int64
  513. }
  514. // AccessibleReposEnv an AccessibleReposEnvironment for the repositories in `org`
  515. // that are accessible to the specified user.
  516. func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) {
  517. teamIDs, err := org.GetUserTeamIDs(userID)
  518. if err != nil {
  519. return nil, err
  520. }
  521. return &accessibleReposEnv{org: org, userID: userID, teamIDs: teamIDs}, nil
  522. }
  523. func (env *accessibleReposEnv) cond() builder.Cond {
  524. var cond builder.Cond = builder.Eq{
  525. "`repository`.owner_id": env.org.ID,
  526. "`repository`.is_private": false,
  527. }
  528. if len(env.teamIDs) > 0 {
  529. cond = cond.Or(builder.In("team_repo.team_id", env.teamIDs))
  530. }
  531. return cond
  532. }
  533. func (env *accessibleReposEnv) CountRepos() (int64, error) {
  534. repoCount, err := x.
  535. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  536. Where(env.cond()).
  537. Distinct("`repository`.id").
  538. Count(&Repository{})
  539. if err != nil {
  540. return 0, fmt.Errorf("count user repositories in organization: %v", err)
  541. }
  542. return repoCount, nil
  543. }
  544. func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
  545. if page <= 0 {
  546. page = 1
  547. }
  548. repoIDs := make([]int64, 0, pageSize)
  549. return repoIDs, x.
  550. Table("repository").
  551. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  552. Where(env.cond()).
  553. GroupBy("`repository`.id,`repository`.updated_unix").
  554. OrderBy("updated_unix DESC").
  555. Limit(pageSize, (page-1)*pageSize).
  556. Cols("`repository`.id").
  557. Find(&repoIDs)
  558. }
  559. func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*Repository, error) {
  560. repoIDs, err := env.RepoIDs(page, pageSize)
  561. if err != nil {
  562. return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err)
  563. }
  564. repos := make([]*Repository, 0, len(repoIDs))
  565. if len(repoIDs) <= 0 {
  566. return repos, nil
  567. }
  568. return repos, x.
  569. In("`repository`.id", repoIDs).
  570. Find(&repos)
  571. }
  572. func (env *accessibleReposEnv) MirrorRepos() ([]*Repository, error) {
  573. repos := make([]*Repository, 0, 10)
  574. return repos, x.
  575. Select("`repository`.*").
  576. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true).
  577. Where(env.cond()).
  578. GroupBy("`repository`.id").
  579. OrderBy("updated_unix DESC").
  580. Find(&repos)
  581. }