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.

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