org.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. return err
  303. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  304. return err
  305. }
  306. return sess.Commit()
  307. }
  308. // RemoveOrgUser removes user from given organization.
  309. func RemoveOrgUser(orgID, userID int64) error {
  310. ou := new(OrgUser)
  311. has, err := x.Where("uid=?", userID).And("org_id=?", orgID).Get(ou)
  312. if err != nil {
  313. return fmt.Errorf("get org-user: %v", err)
  314. } else if !has {
  315. return nil
  316. }
  317. user, err := GetUserByID(userID)
  318. if err != nil {
  319. return fmt.Errorf("GetUserByID [%d]: %v", userID, err)
  320. }
  321. org, err := GetUserByID(orgID)
  322. if err != nil {
  323. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  324. }
  325. // FIXME: only need to get IDs here, not all fields of repository.
  326. repos, _, err := org.GetUserRepositories(user.ID, 1, org.NumRepos)
  327. if err != nil {
  328. return fmt.Errorf("GetUserRepositories [%d]: %v", user.ID, err)
  329. }
  330. // Check if the user to delete is the last member in owner team.
  331. if IsOrganizationOwner(orgID, userID) {
  332. t, err := org.GetOwnerTeam()
  333. if err != nil {
  334. return err
  335. }
  336. if t.NumMembers == 1 {
  337. return ErrLastOrgOwner{UID: userID}
  338. }
  339. }
  340. sess := x.NewSession()
  341. defer sess.Close()
  342. if err := sess.Begin(); err != nil {
  343. return err
  344. }
  345. if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
  346. return err
  347. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  348. return err
  349. }
  350. // Delete all repository accesses and unwatch them.
  351. repoIDs := make([]int64, len(repos))
  352. for i := range repos {
  353. repoIDs = append(repoIDs, repos[i].ID)
  354. if err = watchRepo(sess, user.ID, repos[i].ID, false); err != nil {
  355. return err
  356. }
  357. }
  358. if len(repoIDs) > 0 {
  359. if _, err = sess.Where("user_id = ?", user.ID).In("repo_id", repoIDs).Delete(new(Access)); err != nil {
  360. return err
  361. }
  362. }
  363. // Delete member in his/her teams.
  364. teams, err := getUserTeams(sess, org.ID, user.ID)
  365. if err != nil {
  366. return err
  367. }
  368. for _, t := range teams {
  369. if err = removeTeamMember(sess, org.ID, t.ID, user.ID); err != nil {
  370. return err
  371. }
  372. }
  373. return sess.Commit()
  374. }
  375. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  376. _, err := e.Delete(&TeamRepo{
  377. OrgID: orgID,
  378. RepoID: repoID,
  379. })
  380. return err
  381. }
  382. // RemoveOrgRepo removes all team-repository relations of given organization.
  383. func RemoveOrgRepo(orgID, repoID int64) error {
  384. return removeOrgRepo(x, orgID, repoID)
  385. }
  386. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  387. teams := make([]*Team, 0, org.NumTeams)
  388. return teams, e.Where("team_user.org_id = ?", org.ID).
  389. And("team_user.uid = ?", userID).
  390. Join("INNER", "team_user", "team_user.team_id = team.id").
  391. Cols(cols...).Find(&teams)
  392. }
  393. // GetUserTeamIDs returns of all team IDs of the organization that user is memeber of.
  394. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  395. teams, err := org.getUserTeams(x, userID, "team.id")
  396. if err != nil {
  397. return nil, fmt.Errorf("getUserTeams [%d]: %v", userID, err)
  398. }
  399. teamIDs := make([]int64, len(teams))
  400. for i := range teams {
  401. teamIDs[i] = teams[i].ID
  402. }
  403. return teamIDs, nil
  404. }
  405. // GetTeams returns all teams that belong to organization,
  406. // and that the user has joined.
  407. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  408. return org.getUserTeams(x, userID)
  409. }
  410. // GetUserRepositories returns a range of repositories in organization which the user has access to,
  411. // and total number of records based on given condition.
  412. func (org *User) GetUserRepositories(userID int64, page, pageSize int) ([]*Repository, int64, error) {
  413. teamIDs, err := org.GetUserTeamIDs(userID)
  414. if err != nil {
  415. return nil, 0, fmt.Errorf("GetUserTeamIDs: %v", err)
  416. }
  417. if len(teamIDs) == 0 {
  418. // user has no team but "IN ()" is invalid SQL
  419. teamIDs = []int64{-1} // there is no team with id=-1
  420. }
  421. var teamRepoIDs []int64
  422. if err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs); err != nil {
  423. return nil, 0, fmt.Errorf("get team repository IDs: %v", err)
  424. }
  425. if len(teamRepoIDs) == 0 {
  426. // team has no repo but "IN ()" is invalid SQL
  427. teamRepoIDs = []int64{-1} // there is no repo with id=-1
  428. }
  429. if page <= 0 {
  430. page = 1
  431. }
  432. repos := make([]*Repository, 0, pageSize)
  433. if err = x.Where("owner_id = ?", org.ID).
  434. And(builder.Or(
  435. builder.Expr("is_private = ?", false),
  436. builder.In("id", teamRepoIDs))).
  437. Desc("updated_unix").
  438. Limit(pageSize, (page-1)*pageSize).
  439. Find(&repos); err != nil {
  440. return nil, 0, fmt.Errorf("get user repositories: %v", err)
  441. }
  442. repoCount, err := x.Where("owner_id = ?", org.ID).
  443. And(builder.Or(
  444. builder.Expr("is_private = ?", false),
  445. builder.In("id", teamRepoIDs))).
  446. Count(new(Repository))
  447. if err != nil {
  448. return nil, 0, fmt.Errorf("count user repositories: %v", err)
  449. }
  450. return repos, repoCount, nil
  451. }
  452. // GetUserMirrorRepositories returns mirror repositories of the organization which the user has access to.
  453. func (org *User) GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  454. teamIDs, err := org.GetUserTeamIDs(userID)
  455. if err != nil {
  456. return nil, fmt.Errorf("GetUserTeamIDs: %v", err)
  457. }
  458. if len(teamIDs) == 0 {
  459. teamIDs = []int64{-1}
  460. }
  461. var teamRepoIDs []int64
  462. err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs)
  463. if err != nil {
  464. return nil, fmt.Errorf("get team repository ids: %v", err)
  465. }
  466. if len(teamRepoIDs) == 0 {
  467. // team has no repo but "IN ()" is invalid SQL
  468. teamRepoIDs = []int64{-1} // there is no repo with id=-1
  469. }
  470. repos := make([]*Repository, 0, 10)
  471. if err = x.Where("owner_id = ?", org.ID).
  472. And("is_private = ?", false).
  473. Or(builder.In("id", teamRepoIDs)).
  474. And("is_mirror = ?", true). // Don't move up because it's an independent condition
  475. Desc("updated_unix").
  476. Find(&repos); err != nil {
  477. return nil, fmt.Errorf("get user repositories: %v", err)
  478. }
  479. return repos, nil
  480. }