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