org.go 15 KB

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