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