org.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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/xorm"
  11. log "gopkg.in/clog.v1"
  12. "github.com/gogits/gogs/modules/base"
  13. )
  14. var (
  15. ErrOrgNotExist = errors.New("Organization does not exist")
  16. ErrTeamNotExist = errors.New("Team does not exist")
  17. )
  18. // IsOwnedBy returns true if given user is in the owner team.
  19. func (org *User) IsOwnedBy(uid int64) bool {
  20. return IsOrganizationOwner(org.ID, uid)
  21. }
  22. // IsOrgMember returns true if given user is member of organization.
  23. func (org *User) IsOrgMember(uid int64) bool {
  24. return org.IsOrganization() && IsOrganizationMember(org.ID, uid)
  25. }
  26. func (org *User) getTeam(e Engine, name string) (*Team, error) {
  27. return getTeam(e, org.ID, name)
  28. }
  29. // GetTeam returns named team of organization.
  30. func (org *User) GetTeam(name string) (*Team, error) {
  31. return org.getTeam(x, name)
  32. }
  33. func (org *User) getOwnerTeam(e Engine) (*Team, error) {
  34. return org.getTeam(e, OWNER_TEAM)
  35. }
  36. // GetOwnerTeam returns owner team of organization.
  37. func (org *User) GetOwnerTeam() (*Team, error) {
  38. return org.getOwnerTeam(x)
  39. }
  40. func (org *User) getTeams(e Engine) error {
  41. return e.Where("org_id=?", org.ID).Find(&org.Teams)
  42. }
  43. // GetTeams returns all teams that belong to organization.
  44. func (org *User) GetTeams() error {
  45. return org.getTeams(x)
  46. }
  47. // GetMembers returns all members of organization.
  48. func (org *User) GetMembers() error {
  49. ous, err := GetOrgUsersByOrgID(org.ID)
  50. if err != nil {
  51. return err
  52. }
  53. org.Members = make([]*User, len(ous))
  54. for i, ou := range ous {
  55. org.Members[i], err = GetUserByID(ou.Uid)
  56. if err != nil {
  57. return err
  58. }
  59. }
  60. return nil
  61. }
  62. // AddMember adds new member to organization.
  63. func (org *User) AddMember(uid int64) error {
  64. return AddOrgUser(org.ID, uid)
  65. }
  66. // RemoveMember removes member from organization.
  67. func (org *User) RemoveMember(uid int64) error {
  68. return RemoveOrgUser(org.ID, uid)
  69. }
  70. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  71. return removeOrgRepo(e, org.ID, repoID)
  72. }
  73. // RemoveOrgRepo removes all team-repository relations of organization.
  74. func (org *User) RemoveOrgRepo(repoID int64) error {
  75. return org.removeOrgRepo(x, repoID)
  76. }
  77. // CreateOrganization creates record of a new organization.
  78. func CreateOrganization(org, owner *User) (err error) {
  79. if err = IsUsableUsername(org.Name); err != nil {
  80. return err
  81. }
  82. isExist, err := IsUserExist(0, org.Name)
  83. if err != nil {
  84. return err
  85. } else if isExist {
  86. return ErrUserAlreadyExist{org.Name}
  87. }
  88. org.LowerName = strings.ToLower(org.Name)
  89. if org.Rands, err = GetUserSalt(); err != nil {
  90. return err
  91. }
  92. if org.Salt, err = GetUserSalt(); err != nil {
  93. return err
  94. }
  95. org.UseCustomAvatar = true
  96. org.MaxRepoCreation = -1
  97. org.NumTeams = 1
  98. org.NumMembers = 1
  99. sess := x.NewSession()
  100. defer sessionRelease(sess)
  101. if err = sess.Begin(); err != nil {
  102. return err
  103. }
  104. if _, err = sess.Insert(org); err != nil {
  105. return fmt.Errorf("insert organization: %v", err)
  106. }
  107. org.GenerateRandomAvatar()
  108. // Add initial creator to organization and owner team.
  109. if _, err = sess.Insert(&OrgUser{
  110. Uid: owner.ID,
  111. OrgID: org.ID,
  112. IsOwner: true,
  113. NumTeams: 1,
  114. }); err != nil {
  115. return fmt.Errorf("insert org-user relation: %v", err)
  116. }
  117. // Create default owner team.
  118. t := &Team{
  119. OrgID: org.ID,
  120. LowerName: strings.ToLower(OWNER_TEAM),
  121. Name: OWNER_TEAM,
  122. Authorize: ACCESS_MODE_OWNER,
  123. NumMembers: 1,
  124. }
  125. if _, err = sess.Insert(t); err != nil {
  126. return fmt.Errorf("insert owner team: %v", err)
  127. }
  128. if _, err = sess.Insert(&TeamUser{
  129. UID: owner.ID,
  130. OrgID: org.ID,
  131. TeamID: t.ID,
  132. }); err != nil {
  133. return fmt.Errorf("insert team-user relation: %v", err)
  134. }
  135. if err = os.MkdirAll(UserPath(org.Name), os.ModePerm); err != nil {
  136. return fmt.Errorf("create directory: %v", err)
  137. }
  138. return sess.Commit()
  139. }
  140. // GetOrgByName returns organization by given name.
  141. func GetOrgByName(name string) (*User, error) {
  142. if len(name) == 0 {
  143. return nil, ErrOrgNotExist
  144. }
  145. u := &User{
  146. LowerName: strings.ToLower(name),
  147. Type: USER_TYPE_ORGANIZATION,
  148. }
  149. has, err := x.Get(u)
  150. if err != nil {
  151. return nil, err
  152. } else if !has {
  153. return nil, ErrOrgNotExist
  154. }
  155. return u, nil
  156. }
  157. // CountOrganizations returns number of organizations.
  158. func CountOrganizations() int64 {
  159. count, _ := x.Where("type=1").Count(new(User))
  160. return count
  161. }
  162. // Organizations returns number of organizations in given page.
  163. func Organizations(page, pageSize int) ([]*User, error) {
  164. orgs := make([]*User, 0, pageSize)
  165. return orgs, x.Limit(pageSize, (page-1)*pageSize).Where("type=1").Asc("id").Find(&orgs)
  166. }
  167. // DeleteOrganization completely and permanently deletes everything of organization.
  168. func DeleteOrganization(org *User) (err error) {
  169. if err := DeleteUser(org); err != nil {
  170. return err
  171. }
  172. sess := x.NewSession()
  173. defer sessionRelease(sess)
  174. if err = sess.Begin(); err != nil {
  175. return err
  176. }
  177. if err = deleteBeans(sess,
  178. &Team{OrgID: org.ID},
  179. &OrgUser{OrgID: org.ID},
  180. &TeamUser{OrgID: org.ID},
  181. ); err != nil {
  182. return fmt.Errorf("deleteBeans: %v", err)
  183. }
  184. if err = deleteUser(sess, org); err != nil {
  185. return fmt.Errorf("deleteUser: %v", err)
  186. }
  187. return sess.Commit()
  188. }
  189. // ________ ____ ___
  190. // \_____ \_______ ____ | | \______ ___________
  191. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  192. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  193. // \_______ /__| \___ /|______//____ >\___ >__|
  194. // \/ /_____/ \/ \/
  195. // OrgUser represents an organization-user relation.
  196. type OrgUser struct {
  197. ID int64 `xorm:"pk autoincr"`
  198. Uid int64 `xorm:"INDEX UNIQUE(s)"`
  199. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  200. IsPublic bool
  201. IsOwner bool
  202. NumTeams int
  203. }
  204. // IsOrganizationOwner returns true if given user is in the owner team.
  205. func IsOrganizationOwner(orgId, uid int64) bool {
  206. has, _ := x.Where("is_owner=?", true).And("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  207. return has
  208. }
  209. // IsOrganizationMember returns true if given user is member of organization.
  210. func IsOrganizationMember(orgId, uid int64) bool {
  211. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  212. return has
  213. }
  214. // IsPublicMembership returns true if given user public his/her membership.
  215. func IsPublicMembership(orgId, uid int64) bool {
  216. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
  217. return has
  218. }
  219. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  220. orgs := make([]*User, 0, 10)
  221. if !showAll {
  222. sess.And("`org_user`.is_public=?", true)
  223. }
  224. return orgs, sess.And("`org_user`.uid=?", userID).
  225. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  226. }
  227. // GetOrgsByUserID returns a list of organizations that the given user ID
  228. // has joined.
  229. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  230. return getOrgsByUserID(x.NewSession(), userID, showAll)
  231. }
  232. // GetOrgsByUserIDDesc returns a list of organizations that the given user ID
  233. // has joined, ordered descending by the given condition.
  234. func GetOrgsByUserIDDesc(userID int64, desc string, showAll bool) ([]*User, error) {
  235. return getOrgsByUserID(x.NewSession().Desc(desc), userID, showAll)
  236. }
  237. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  238. orgs := make([]*User, 0, 10)
  239. return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
  240. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  241. }
  242. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  243. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  244. sess := x.NewSession()
  245. return getOwnedOrgsByUserID(sess, userID)
  246. }
  247. // GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
  248. // given user ID, ordered descending by the given condition.
  249. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  250. sess := x.NewSession()
  251. return getOwnedOrgsByUserID(sess.Desc(desc), userID)
  252. }
  253. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  254. func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
  255. ous := make([]*OrgUser, 0, 10)
  256. sess := x.Where("uid=?", uid)
  257. if !all {
  258. // Only show public organizations
  259. sess.And("is_public=?", true)
  260. }
  261. err := sess.Find(&ous)
  262. return ous, err
  263. }
  264. func getOrgUsersByOrgID(e Engine, orgID int64) ([]*OrgUser, error) {
  265. orgUsers := make([]*OrgUser, 0, 10)
  266. return orgUsers, e.Where("org_id=?", orgID).Find(&orgUsers)
  267. }
  268. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  269. func GetOrgUsersByOrgID(orgID int64) ([]*OrgUser, error) {
  270. return getOrgUsersByOrgID(x, orgID)
  271. }
  272. // ChangeOrgUserStatus changes public or private membership status.
  273. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  274. ou := new(OrgUser)
  275. has, err := x.Where("uid=?", uid).And("org_id=?", orgID).Get(ou)
  276. if err != nil {
  277. return err
  278. } else if !has {
  279. return nil
  280. }
  281. ou.IsPublic = public
  282. _, err = x.Id(ou.ID).AllCols().Update(ou)
  283. return err
  284. }
  285. // AddOrgUser adds new user to given organization.
  286. func AddOrgUser(orgID, uid int64) error {
  287. if IsOrganizationMember(orgID, uid) {
  288. return nil
  289. }
  290. sess := x.NewSession()
  291. defer sess.Close()
  292. if err := sess.Begin(); err != nil {
  293. return err
  294. }
  295. ou := &OrgUser{
  296. Uid: uid,
  297. OrgID: orgID,
  298. }
  299. if _, err := sess.Insert(ou); err != nil {
  300. sess.Rollback()
  301. return err
  302. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  303. sess.Rollback()
  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 sessionRelease(sess)
  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
  411. // that the user with the given userID has access to,
  412. // and total number of records based on given condition.
  413. func (org *User) GetUserRepositories(userID int64, page, pageSize int) ([]*Repository, int64, error) {
  414. teamIDs, err := org.GetUserTeamIDs(userID)
  415. if err != nil {
  416. return nil, 0, fmt.Errorf("GetUserTeamIDs: %v", err)
  417. }
  418. if len(teamIDs) == 0 {
  419. // user has no team but "IN ()" is invalid SQL
  420. teamIDs = []int64{-1} // there is no repo with id=-1
  421. }
  422. if page <= 0 {
  423. page = 1
  424. }
  425. repos := make([]*Repository, 0, pageSize)
  426. // FIXME: use XORM chain operations instead of raw SQL.
  427. if err = x.Sql(fmt.Sprintf(`SELECT repository.* FROM repository
  428. INNER JOIN team_repo
  429. ON team_repo.repo_id = repository.id
  430. WHERE (repository.owner_id = ? AND repository.is_private = ?) OR team_repo.team_id IN (%s)
  431. GROUP BY repository.id
  432. ORDER BY updated_unix DESC
  433. LIMIT %d OFFSET %d`,
  434. strings.Join(base.Int64sToStrings(teamIDs), ","), pageSize, (page-1)*pageSize),
  435. org.ID, false).Find(&repos); err != nil {
  436. return nil, 0, fmt.Errorf("get repositories: %v", err)
  437. }
  438. results, err := x.Query(fmt.Sprintf(`SELECT repository.id FROM repository
  439. INNER JOIN team_repo
  440. ON team_repo.repo_id = repository.id
  441. WHERE (repository.owner_id = ? AND repository.is_private = ?) OR team_repo.team_id IN (%s)
  442. GROUP BY repository.id
  443. ORDER BY updated_unix DESC`,
  444. strings.Join(base.Int64sToStrings(teamIDs), ",")),
  445. org.ID, false)
  446. if err != nil {
  447. log.Error(4, "count user repositories in organization: %v", err)
  448. }
  449. return repos, int64(len(results)), nil
  450. }
  451. // GetUserRepositories returns mirror repositories of the organization
  452. // that the user with the given userID 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. repos := make([]*Repository, 0, 10)
  462. if err = x.Sql(fmt.Sprintf(`SELECT repository.* FROM repository
  463. INNER JOIN team_repo
  464. ON team_repo.repo_id = repository.id AND repository.is_mirror = ?
  465. WHERE (repository.owner_id = ? AND repository.is_private = ?) OR team_repo.team_id IN (%s)
  466. GROUP BY repository.id
  467. ORDER BY updated_unix DESC`,
  468. strings.Join(base.Int64sToStrings(teamIDs), ",")),
  469. true, org.ID, false).Find(&repos); err != nil {
  470. return nil, fmt.Errorf("get repositories: %v", err)
  471. }
  472. return repos, nil
  473. }