org.go 16 KB

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