org.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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/builder"
  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(userID int64) bool {
  19. return IsOrganizationOwner(org.ID, userID)
  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 getTeamOfOrgByName(e, org.ID, name)
  27. }
  28. // GetTeamOfOrgByName 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) (err error) {
  40. org.Teams, err = getTeamsByOrgID(e, org.ID)
  41. return err
  42. }
  43. // GetTeams returns all teams that belong to organization.
  44. func (org *User) GetTeams() error {
  45. return org.getTeams(x)
  46. }
  47. // TeamsHaveAccessToRepo returns all teamsthat have given access level to the repository.
  48. func (org *User) TeamsHaveAccessToRepo(repoID int64, mode AccessMode) ([]*Team, error) {
  49. return GetTeamsHaveAccessToRepo(org.ID, repoID, mode)
  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. org.Members = make([]*User, len(ous))
  58. for i, ou := range ous {
  59. org.Members[i], err = GetUserByID(ou.Uid)
  60. if err != nil {
  61. return err
  62. }
  63. }
  64. return nil
  65. }
  66. // AddMember adds new member to organization.
  67. func (org *User) AddMember(uid int64) error {
  68. return AddOrgUser(org.ID, uid)
  69. }
  70. // RemoveMember removes member from organization.
  71. func (org *User) RemoveMember(uid int64) error {
  72. return RemoveOrgUser(org.ID, uid)
  73. }
  74. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  75. return removeOrgRepo(e, org.ID, repoID)
  76. }
  77. // RemoveOrgRepo removes all team-repository relations of organization.
  78. func (org *User) RemoveOrgRepo(repoID int64) error {
  79. return org.removeOrgRepo(x, repoID)
  80. }
  81. // CreateOrganization creates record of a new organization.
  82. func CreateOrganization(org, owner *User) (err error) {
  83. if err = IsUsableUsername(org.Name); err != nil {
  84. return err
  85. }
  86. isExist, err := IsUserExist(0, org.Name)
  87. if err != nil {
  88. return err
  89. } else if isExist {
  90. return ErrUserAlreadyExist{org.Name}
  91. }
  92. org.LowerName = strings.ToLower(org.Name)
  93. if org.Rands, err = GetUserSalt(); err != nil {
  94. return err
  95. }
  96. if org.Salt, err = GetUserSalt(); err != nil {
  97. return err
  98. }
  99. org.UseCustomAvatar = true
  100. org.MaxRepoCreation = -1
  101. org.NumTeams = 1
  102. org.NumMembers = 1
  103. sess := x.NewSession()
  104. defer sess.Close()
  105. if err = sess.Begin(); err != nil {
  106. return err
  107. }
  108. if _, err = sess.Insert(org); err != nil {
  109. return fmt.Errorf("insert organization: %v", err)
  110. }
  111. org.GenerateRandomAvatar()
  112. // Add initial creator to organization and owner team.
  113. if _, err = sess.Insert(&OrgUser{
  114. Uid: owner.ID,
  115. OrgID: org.ID,
  116. IsOwner: true,
  117. NumTeams: 1,
  118. }); err != nil {
  119. return fmt.Errorf("insert org-user relation: %v", err)
  120. }
  121. // Create default owner team.
  122. t := &Team{
  123. OrgID: org.ID,
  124. LowerName: strings.ToLower(OWNER_TEAM),
  125. Name: OWNER_TEAM,
  126. Authorize: ACCESS_MODE_OWNER,
  127. NumMembers: 1,
  128. }
  129. if _, err = sess.Insert(t); err != nil {
  130. return fmt.Errorf("insert owner team: %v", err)
  131. }
  132. if _, err = sess.Insert(&TeamUser{
  133. UID: owner.ID,
  134. OrgID: org.ID,
  135. TeamID: t.ID,
  136. }); err != nil {
  137. return fmt.Errorf("insert team-user relation: %v", err)
  138. }
  139. if err = os.MkdirAll(UserPath(org.Name), os.ModePerm); err != nil {
  140. return fmt.Errorf("create directory: %v", err)
  141. }
  142. return sess.Commit()
  143. }
  144. // GetOrgByName returns organization by given name.
  145. func GetOrgByName(name string) (*User, error) {
  146. if len(name) == 0 {
  147. return nil, ErrOrgNotExist
  148. }
  149. u := &User{
  150. LowerName: strings.ToLower(name),
  151. Type: USER_TYPE_ORGANIZATION,
  152. }
  153. has, err := x.Get(u)
  154. if err != nil {
  155. return nil, err
  156. } else if !has {
  157. return nil, ErrOrgNotExist
  158. }
  159. return u, nil
  160. }
  161. // CountOrganizations returns number of organizations.
  162. func CountOrganizations() int64 {
  163. count, _ := x.Where("type=1").Count(new(User))
  164. return count
  165. }
  166. // Organizations returns number of organizations in given page.
  167. func Organizations(page, pageSize int) ([]*User, error) {
  168. orgs := make([]*User, 0, pageSize)
  169. return orgs, x.Limit(pageSize, (page-1)*pageSize).Where("type=1").Asc("id").Find(&orgs)
  170. }
  171. // DeleteOrganization completely and permanently deletes everything of organization.
  172. func DeleteOrganization(org *User) (err error) {
  173. if err := DeleteUser(org); err != nil {
  174. return err
  175. }
  176. sess := x.NewSession()
  177. defer sess.Close()
  178. if err = sess.Begin(); err != nil {
  179. return err
  180. }
  181. if err = deleteBeans(sess,
  182. &Team{OrgID: org.ID},
  183. &OrgUser{OrgID: org.ID},
  184. &TeamUser{OrgID: org.ID},
  185. ); err != nil {
  186. return fmt.Errorf("deleteBeans: %v", err)
  187. }
  188. if err = deleteUser(sess, org); err != nil {
  189. return fmt.Errorf("deleteUser: %v", err)
  190. }
  191. return sess.Commit()
  192. }
  193. // ________ ____ ___
  194. // \_____ \_______ ____ | | \______ ___________
  195. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  196. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  197. // \_______ /__| \___ /|______//____ >\___ >__|
  198. // \/ /_____/ \/ \/
  199. // OrgUser represents an organization-user relation.
  200. type OrgUser struct {
  201. ID int64
  202. Uid int64 `xorm:"INDEX UNIQUE(s)"`
  203. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  204. IsPublic bool
  205. IsOwner bool
  206. NumTeams int
  207. }
  208. // IsOrganizationOwner returns true if given user is in the owner team.
  209. func IsOrganizationOwner(orgID, userID int64) bool {
  210. has, _ := x.Where("is_owner = ?", true).And("uid = ?", userID).And("org_id = ?", orgID).Get(new(OrgUser))
  211. return has
  212. }
  213. // IsOrganizationMember returns true if given user is member of organization.
  214. func IsOrganizationMember(orgId, uid int64) bool {
  215. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  216. return has
  217. }
  218. // IsPublicMembership returns true if given user public his/her membership.
  219. func IsPublicMembership(orgId, uid int64) bool {
  220. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
  221. return has
  222. }
  223. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  224. orgs := make([]*User, 0, 10)
  225. if !showAll {
  226. sess.And("`org_user`.is_public=?", true)
  227. }
  228. return orgs, sess.And("`org_user`.uid=?", userID).
  229. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  230. }
  231. // GetOrgsByUserID returns a list of organizations that the given user ID
  232. // has joined.
  233. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  234. return getOrgsByUserID(x.NewSession(), userID, showAll)
  235. }
  236. // GetOrgsByUserIDDesc returns a list of organizations that the given user ID
  237. // has joined, ordered descending by the given condition.
  238. func GetOrgsByUserIDDesc(userID int64, desc string, showAll bool) ([]*User, error) {
  239. return getOrgsByUserID(x.NewSession().Desc(desc), userID, showAll)
  240. }
  241. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  242. orgs := make([]*User, 0, 10)
  243. return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
  244. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  245. }
  246. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  247. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  248. sess := x.NewSession()
  249. return getOwnedOrgsByUserID(sess, userID)
  250. }
  251. // GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
  252. // given user ID, ordered descending by the given condition.
  253. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  254. sess := x.NewSession()
  255. return getOwnedOrgsByUserID(sess.Desc(desc), userID)
  256. }
  257. // GetOrgIDsByUserID returns a list of organization IDs that user belongs to.
  258. // The showPrivate indicates whether to include private memberships.
  259. func GetOrgIDsByUserID(userID int64, showPrivate bool) ([]int64, error) {
  260. orgIDs := make([]int64, 0, 5)
  261. sess := x.Table("org_user").Where("uid = ?", userID)
  262. if !showPrivate {
  263. sess.And("is_public = ?", true)
  264. }
  265. return orgIDs, sess.Distinct("org_id").Find(&orgIDs)
  266. }
  267. func getOrgUsersByOrgID(e Engine, orgID int64) ([]*OrgUser, error) {
  268. orgUsers := make([]*OrgUser, 0, 10)
  269. return orgUsers, e.Where("org_id=?", orgID).Find(&orgUsers)
  270. }
  271. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  272. func GetOrgUsersByOrgID(orgID int64) ([]*OrgUser, error) {
  273. return getOrgUsersByOrgID(x, orgID)
  274. }
  275. // ChangeOrgUserStatus changes public or private membership status.
  276. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  277. ou := new(OrgUser)
  278. has, err := x.Where("uid=?", uid).And("org_id=?", orgID).Get(ou)
  279. if err != nil {
  280. return err
  281. } else if !has {
  282. return nil
  283. }
  284. ou.IsPublic = public
  285. _, err = x.Id(ou.ID).AllCols().Update(ou)
  286. return err
  287. }
  288. // AddOrgUser adds new user to given organization.
  289. func AddOrgUser(orgID, uid int64) error {
  290. if IsOrganizationMember(orgID, uid) {
  291. return nil
  292. }
  293. sess := x.NewSession()
  294. defer sess.Close()
  295. if err := sess.Begin(); err != nil {
  296. return err
  297. }
  298. ou := &OrgUser{
  299. Uid: uid,
  300. OrgID: orgID,
  301. }
  302. if _, err := sess.Insert(ou); err != nil {
  303. sess.Rollback()
  304. return err
  305. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  306. sess.Rollback()
  307. return err
  308. }
  309. return sess.Commit()
  310. }
  311. // RemoveOrgUser removes user from given organization.
  312. func RemoveOrgUser(orgID, userID int64) error {
  313. ou := new(OrgUser)
  314. has, err := x.Where("uid=?", userID).And("org_id=?", orgID).Get(ou)
  315. if err != nil {
  316. return fmt.Errorf("get org-user: %v", err)
  317. } else if !has {
  318. return nil
  319. }
  320. user, err := GetUserByID(userID)
  321. if err != nil {
  322. return fmt.Errorf("GetUserByID [%d]: %v", userID, err)
  323. }
  324. org, err := GetUserByID(orgID)
  325. if err != nil {
  326. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  327. }
  328. // FIXME: only need to get IDs here, not all fields of repository.
  329. repos, _, err := org.GetUserRepositories(user.ID, 1, org.NumRepos)
  330. if err != nil {
  331. return fmt.Errorf("GetUserRepositories [%d]: %v", user.ID, err)
  332. }
  333. // Check if the user to delete is the last member in owner team.
  334. if IsOrganizationOwner(orgID, userID) {
  335. t, err := org.GetOwnerTeam()
  336. if err != nil {
  337. return err
  338. }
  339. if t.NumMembers == 1 {
  340. return ErrLastOrgOwner{UID: userID}
  341. }
  342. }
  343. sess := x.NewSession()
  344. defer sess.Close()
  345. if err := sess.Begin(); err != nil {
  346. return err
  347. }
  348. if _, err := sess.Id(ou.ID).Delete(ou); err != nil {
  349. return err
  350. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  351. return err
  352. }
  353. // Delete all repository accesses and unwatch them.
  354. repoIDs := make([]int64, len(repos))
  355. for i := range repos {
  356. repoIDs = append(repoIDs, repos[i].ID)
  357. if err = watchRepo(sess, user.ID, repos[i].ID, false); err != nil {
  358. return err
  359. }
  360. }
  361. if len(repoIDs) > 0 {
  362. if _, err = sess.Where("user_id = ?", user.ID).In("repo_id", repoIDs).Delete(new(Access)); err != nil {
  363. return err
  364. }
  365. }
  366. // Delete member in his/her teams.
  367. teams, err := getUserTeams(sess, org.ID, user.ID)
  368. if err != nil {
  369. return err
  370. }
  371. for _, t := range teams {
  372. if err = removeTeamMember(sess, org.ID, t.ID, user.ID); err != nil {
  373. return err
  374. }
  375. }
  376. return sess.Commit()
  377. }
  378. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  379. _, err := e.Delete(&TeamRepo{
  380. OrgID: orgID,
  381. RepoID: repoID,
  382. })
  383. return err
  384. }
  385. // RemoveOrgRepo removes all team-repository relations of given organization.
  386. func RemoveOrgRepo(orgID, repoID int64) error {
  387. return removeOrgRepo(x, orgID, repoID)
  388. }
  389. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  390. teams := make([]*Team, 0, org.NumTeams)
  391. return teams, e.Where("team_user.org_id = ?", org.ID).
  392. And("team_user.uid = ?", userID).
  393. Join("INNER", "team_user", "team_user.team_id = team.id").
  394. Cols(cols...).Find(&teams)
  395. }
  396. // GetUserTeamIDs returns of all team IDs of the organization that user is memeber of.
  397. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  398. teams, err := org.getUserTeams(x, userID, "team.id")
  399. if err != nil {
  400. return nil, fmt.Errorf("getUserTeams [%d]: %v", userID, err)
  401. }
  402. teamIDs := make([]int64, len(teams))
  403. for i := range teams {
  404. teamIDs[i] = teams[i].ID
  405. }
  406. return teamIDs, nil
  407. }
  408. // GetTeams returns all teams that belong to organization,
  409. // and that the user has joined.
  410. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  411. return org.getUserTeams(x, userID)
  412. }
  413. // GetUserRepositories returns a range of repositories in organization which the user has access to,
  414. // and total number of records based on given condition.
  415. func (org *User) GetUserRepositories(userID int64, page, pageSize int) ([]*Repository, int64, error) {
  416. teamIDs, err := org.GetUserTeamIDs(userID)
  417. if err != nil {
  418. return nil, 0, fmt.Errorf("GetUserTeamIDs: %v", err)
  419. }
  420. if len(teamIDs) == 0 {
  421. // user has no team but "IN ()" is invalid SQL
  422. teamIDs = []int64{-1} // there is no team with id=-1
  423. }
  424. var teamRepoIDs []int64
  425. if err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs); err != nil {
  426. return nil, 0, fmt.Errorf("get team repository IDs: %v", err)
  427. }
  428. if len(teamRepoIDs) == 0 {
  429. // team has no repo but "IN ()" is invalid SQL
  430. teamRepoIDs = []int64{-1} // there is no repo with id=-1
  431. }
  432. if page <= 0 {
  433. page = 1
  434. }
  435. repos := make([]*Repository, 0, pageSize)
  436. if err = x.Where("owner_id = ?", org.ID).
  437. And("is_private = ?", false).
  438. Or(builder.In("id", teamRepoIDs)).
  439. Desc("updated_unix").
  440. Limit(pageSize, (page-1)*pageSize).
  441. Find(&repos); err != nil {
  442. return nil, 0, fmt.Errorf("get user repositories: %v", err)
  443. }
  444. repoCount, err := x.Where("owner_id = ?", org.ID).
  445. And("is_private = ?", false).
  446. Or(builder.In("id", teamRepoIDs)).
  447. Count(new(Repository))
  448. if err != nil {
  449. return nil, 0, fmt.Errorf("count user repositories: %v", err)
  450. }
  451. return repos, repoCount, nil
  452. }
  453. // GetUserMirrorRepositories returns mirror repositories of the organization which the user has access to.
  454. func (org *User) GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  455. teamIDs, err := org.GetUserTeamIDs(userID)
  456. if err != nil {
  457. return nil, fmt.Errorf("GetUserTeamIDs: %v", err)
  458. }
  459. if len(teamIDs) == 0 {
  460. teamIDs = []int64{-1}
  461. }
  462. var teamRepoIDs []int64
  463. err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs)
  464. if err != nil {
  465. return nil, fmt.Errorf("get team repository ids: %v", err)
  466. }
  467. if len(teamRepoIDs) == 0 {
  468. // team has no repo but "IN ()" is invalid SQL
  469. teamRepoIDs = []int64{-1} // there is no repo with id=-1
  470. }
  471. repos := make([]*Repository, 0, 10)
  472. if err = x.Where("owner_id = ?", org.ID).
  473. And("is_private = ?", false).
  474. Or(builder.In("id", teamRepoIDs)).
  475. And("is_mirror = ?", true). // Don't move up because it's an independent condition
  476. Desc("updated_unix").
  477. Find(&repos); err != nil {
  478. return nil, fmt.Errorf("get user repositories: %v", err)
  479. }
  480. return repos, nil
  481. }