org.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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/Unknwon/com"
  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 getTeam(e, org.Id, name)
  27. }
  28. // GetTeam 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) error {
  40. return e.Where("org_id=?", org.Id).Find(&org.Teams)
  41. }
  42. // GetTeams returns all teams that belong to organization.
  43. func (org *User) GetTeams() error {
  44. return org.getTeams(x)
  45. }
  46. // GetMembers returns all members of organization.
  47. func (org *User) GetMembers() error {
  48. ous, err := GetOrgUsersByOrgID(org.Id)
  49. if err != nil {
  50. return err
  51. }
  52. org.Members = make([]*User, len(ous))
  53. for i, ou := range ous {
  54. org.Members[i], err = GetUserByID(ou.Uid)
  55. if err != nil {
  56. return err
  57. }
  58. }
  59. return nil
  60. }
  61. // AddMember adds new member to organization.
  62. func (org *User) AddMember(uid int64) error {
  63. return AddOrgUser(org.Id, uid)
  64. }
  65. // RemoveMember removes member from organization.
  66. func (org *User) RemoveMember(uid int64) error {
  67. return RemoveOrgUser(org.Id, uid)
  68. }
  69. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  70. return removeOrgRepo(e, org.Id, repoID)
  71. }
  72. // RemoveOrgRepo removes all team-repository relations of organization.
  73. func (org *User) RemoveOrgRepo(repoID int64) error {
  74. return org.removeOrgRepo(x, repoID)
  75. }
  76. // CreateOrganization creates record of a new organization.
  77. func CreateOrganization(org, owner *User) (err error) {
  78. if err = IsUsableName(org.Name); err != nil {
  79. return err
  80. }
  81. isExist, err := IsUserExist(0, org.Name)
  82. if err != nil {
  83. return err
  84. } else if isExist {
  85. return ErrUserAlreadyExist{org.Name}
  86. }
  87. org.LowerName = strings.ToLower(org.Name)
  88. org.FullName = org.Name
  89. org.Rands = GetUserSalt()
  90. org.Salt = GetUserSalt()
  91. org.UseCustomAvatar = true
  92. org.MaxRepoCreation = -1
  93. org.NumTeams = 1
  94. org.NumMembers = 1
  95. sess := x.NewSession()
  96. defer sessionRelease(sess)
  97. if err = sess.Begin(); err != nil {
  98. return err
  99. }
  100. if _, err = sess.Insert(org); err != nil {
  101. return fmt.Errorf("insert organization: %v", err)
  102. }
  103. org.GenerateRandomAvatar()
  104. // Add initial creator to organization and owner team.
  105. if _, err = sess.Insert(&OrgUser{
  106. Uid: owner.Id,
  107. OrgID: org.Id,
  108. IsOwner: true,
  109. NumTeams: 1,
  110. }); err != nil {
  111. return fmt.Errorf("insert org-user relation: %v", err)
  112. }
  113. // Create default owner team.
  114. t := &Team{
  115. OrgID: org.Id,
  116. LowerName: strings.ToLower(OWNER_TEAM),
  117. Name: OWNER_TEAM,
  118. Authorize: ACCESS_MODE_OWNER,
  119. NumMembers: 1,
  120. }
  121. if _, err = sess.Insert(t); err != nil {
  122. return fmt.Errorf("insert owner team: %v", err)
  123. }
  124. if _, err = sess.Insert(&TeamUser{
  125. Uid: owner.Id,
  126. OrgID: org.Id,
  127. TeamID: t.ID,
  128. }); err != nil {
  129. return fmt.Errorf("insert team-user relation: %v", err)
  130. }
  131. if err = os.MkdirAll(UserPath(org.Name), os.ModePerm); err != nil {
  132. return fmt.Errorf("create directory: %v", err)
  133. }
  134. return sess.Commit()
  135. }
  136. // GetOrgByName returns organization by given name.
  137. func GetOrgByName(name string) (*User, error) {
  138. if len(name) == 0 {
  139. return nil, ErrOrgNotExist
  140. }
  141. u := &User{
  142. LowerName: strings.ToLower(name),
  143. Type: USER_TYPE_ORGANIZATION,
  144. }
  145. has, err := x.Get(u)
  146. if err != nil {
  147. return nil, err
  148. } else if !has {
  149. return nil, ErrOrgNotExist
  150. }
  151. return u, nil
  152. }
  153. // CountOrganizations returns number of organizations.
  154. func CountOrganizations() int64 {
  155. count, _ := x.Where("type=1").Count(new(User))
  156. return count
  157. }
  158. // Organizations returns number of organizations in given page.
  159. func Organizations(page, pageSize int) ([]*User, error) {
  160. orgs := make([]*User, 0, pageSize)
  161. return orgs, x.Limit(pageSize, (page-1)*pageSize).Where("type=1").Asc("id").Find(&orgs)
  162. }
  163. // DeleteOrganization completely and permanently deletes everything of organization.
  164. func DeleteOrganization(org *User) (err error) {
  165. if err := DeleteUser(org); err != nil {
  166. return err
  167. }
  168. sess := x.NewSession()
  169. defer sessionRelease(sess)
  170. if err = sess.Begin(); err != nil {
  171. return err
  172. }
  173. if err = deleteBeans(sess,
  174. &Team{OrgID: org.Id},
  175. &OrgUser{OrgID: org.Id},
  176. &TeamUser{OrgID: org.Id},
  177. ); err != nil {
  178. return fmt.Errorf("deleteBeans: %v", err)
  179. }
  180. if err = deleteUser(sess, org); err != nil {
  181. return fmt.Errorf("deleteUser: %v", err)
  182. }
  183. return sess.Commit()
  184. }
  185. // ________ ____ ___
  186. // \_____ \_______ ____ | | \______ ___________
  187. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  188. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  189. // \_______ /__| \___ /|______//____ >\___ >__|
  190. // \/ /_____/ \/ \/
  191. // OrgUser represents an organization-user relation.
  192. type OrgUser struct {
  193. ID int64 `xorm:"pk autoincr"`
  194. Uid int64 `xorm:"INDEX UNIQUE(s)"`
  195. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  196. IsPublic bool
  197. IsOwner bool
  198. NumTeams int
  199. }
  200. // IsOrganizationOwner returns true if given user is in the owner team.
  201. func IsOrganizationOwner(orgId, uid int64) bool {
  202. has, _ := x.Where("is_owner=?", true).And("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  203. return has
  204. }
  205. // IsOrganizationMember returns true if given user is member of organization.
  206. func IsOrganizationMember(orgId, uid int64) bool {
  207. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
  208. return has
  209. }
  210. // IsPublicMembership returns true if given user public his/her membership.
  211. func IsPublicMembership(orgId, uid int64) bool {
  212. has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
  213. return has
  214. }
  215. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  216. orgs := make([]*User, 0, 10)
  217. if !showAll {
  218. sess.And("`org_user`.is_public=?", true)
  219. }
  220. return orgs, sess.And("`org_user`.uid=?", userID).
  221. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  222. }
  223. // GetOrgsByUserID returns a list of organizations that the given user ID
  224. // has joined.
  225. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  226. return getOrgsByUserID(x.NewSession(), userID, showAll)
  227. }
  228. // GetOrgsByUserIDDesc returns a list of organizations that the given user ID
  229. // has joined, ordered descending by the given condition.
  230. func GetOrgsByUserIDDesc(userID int64, desc string, showAll bool) ([]*User, error) {
  231. return getOrgsByUserID(x.NewSession().Desc(desc), userID, showAll)
  232. }
  233. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  234. orgs := make([]*User, 0, 10)
  235. return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
  236. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  237. }
  238. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  239. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  240. sess := x.NewSession()
  241. return getOwnedOrgsByUserID(sess, userID)
  242. }
  243. // GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
  244. // given user ID, ordered descending by the given condition.
  245. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  246. sess := x.NewSession()
  247. return getOwnedOrgsByUserID(sess.Desc(desc), userID)
  248. }
  249. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  250. func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
  251. ous := make([]*OrgUser, 0, 10)
  252. sess := x.Where("uid=?", uid)
  253. if !all {
  254. // Only show public organizations
  255. sess.And("is_public=?", true)
  256. }
  257. err := sess.Find(&ous)
  258. return ous, err
  259. }
  260. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  261. func GetOrgUsersByOrgID(orgID int64) ([]*OrgUser, error) {
  262. ous := make([]*OrgUser, 0, 10)
  263. err := x.Where("org_id=?", orgID).Find(&ous)
  264. return ous, err
  265. }
  266. // ChangeOrgUserStatus changes public or private membership status.
  267. func ChangeOrgUserStatus(orgId, uid int64, public bool) error {
  268. ou := new(OrgUser)
  269. has, err := x.Where("uid=?", uid).And("org_id=?", orgId).Get(ou)
  270. if err != nil {
  271. return err
  272. } else if !has {
  273. return nil
  274. }
  275. ou.IsPublic = public
  276. _, err = x.Id(ou.ID).AllCols().Update(ou)
  277. return err
  278. }
  279. // AddOrgUser adds new user to given organization.
  280. func AddOrgUser(orgId, uid int64) error {
  281. if IsOrganizationMember(orgId, uid) {
  282. return nil
  283. }
  284. sess := x.NewSession()
  285. defer sess.Close()
  286. if err := sess.Begin(); err != nil {
  287. return err
  288. }
  289. ou := &OrgUser{
  290. Uid: uid,
  291. OrgID: orgId,
  292. }
  293. if _, err := sess.Insert(ou); err != nil {
  294. sess.Rollback()
  295. return err
  296. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgId); err != nil {
  297. sess.Rollback()
  298. return err
  299. }
  300. return sess.Commit()
  301. }
  302. // RemoveOrgUser removes user from given organization.
  303. func RemoveOrgUser(orgId, uid int64) error {
  304. ou := new(OrgUser)
  305. has, err := x.Where("uid=?", uid).And("org_id=?", orgId).Get(ou)
  306. if err != nil {
  307. return fmt.Errorf("get org-user: %v", err)
  308. } else if !has {
  309. return nil
  310. }
  311. u, err := GetUserByID(uid)
  312. if err != nil {
  313. return fmt.Errorf("GetUserById: %v", err)
  314. }
  315. org, err := GetUserByID(orgId)
  316. if err != nil {
  317. return fmt.Errorf("get organization: %v", err)
  318. } else if err = org.GetRepositories(); err != nil {
  319. return fmt.Errorf("GetRepositories: %v", err)
  320. }
  321. // Check if the user to delete is the last member in owner team.
  322. if IsOrganizationOwner(orgId, uid) {
  323. t, err := org.GetOwnerTeam()
  324. if err != nil {
  325. return err
  326. }
  327. if t.NumMembers == 1 {
  328. return ErrLastOrgOwner{UID: uid}
  329. }
  330. }
  331. sess := x.NewSession()
  332. defer sessionRelease(sess)
  333. if err := sess.Begin(); err != nil {
  334. return err
  335. }
  336. if _, err := sess.Id(ou.ID).Delete(ou); err != nil {
  337. return err
  338. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgId); err != nil {
  339. return err
  340. }
  341. // Delete all repository accesses.
  342. access := &Access{UserID: u.Id}
  343. for _, repo := range org.Repos {
  344. access.RepoID = repo.ID
  345. if _, err = sess.Delete(access); err != nil {
  346. return err
  347. } else if err = watchRepo(sess, u.Id, repo.ID, false); err != nil {
  348. return err
  349. }
  350. }
  351. // Delete member in his/her teams.
  352. teams, err := getUserTeams(sess, org.Id, u.Id)
  353. if err != nil {
  354. return err
  355. }
  356. for _, t := range teams {
  357. if err = removeTeamMember(sess, org.Id, t.ID, u.Id); err != nil {
  358. return err
  359. }
  360. }
  361. return sess.Commit()
  362. }
  363. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  364. _, err := e.Delete(&TeamRepo{
  365. OrgID: orgID,
  366. RepoID: repoID,
  367. })
  368. return err
  369. }
  370. // RemoveOrgRepo removes all team-repository relations of given organization.
  371. func RemoveOrgRepo(orgID, repoID int64) error {
  372. return removeOrgRepo(x, orgID, repoID)
  373. }
  374. // GetUserRepositories gets all repositories of an organization,
  375. // that the user with the given userID has access to.
  376. func (org *User) GetUserRepositories(userID int64) (err error) {
  377. teams := make([]*Team, 0, org.NumTeams)
  378. if err = x.Sql(`SELECT team.id FROM team
  379. INNER JOIN team_user ON team_user.team_id = team.id
  380. WHERE team_user.org_id = ? AND team_user.uid = ?`, org.Id, userID).Find(&teams); err != nil {
  381. return fmt.Errorf("get teams: %v", err)
  382. }
  383. teamIDs := make([]string, len(teams))
  384. for i := range teams {
  385. teamIDs[i] = com.ToStr(teams[i].ID)
  386. }
  387. if len(teamIDs) == 0 {
  388. // user has no team but "IN ()" is invalid SQL
  389. teamIDs = append(teamIDs, "-1") // there is no repo with id=-1
  390. }
  391. repos := make([]*Repository, 0, 5)
  392. if err = x.Sql(fmt.Sprintf(`SELECT repository.* FROM repository
  393. INNER JOIN team_repo ON team_repo.repo_id = repository.id
  394. WHERE (repository.owner_id = ? AND repository.is_private = ?) OR team_repo.team_id IN (%s)
  395. GROUP BY repository.id`, strings.Join(teamIDs, ",")), org.Id, false).Find(&repos); err != nil {
  396. return fmt.Errorf("get repositories: %v", err)
  397. }
  398. org.Repos = repos
  399. // FIXME: should I change this value inside method,
  400. // or only in location of caller where it's really needed?
  401. org.NumRepos = len(org.Repos)
  402. return nil
  403. }
  404. // GetTeams returns all teams that belong to organization,
  405. // and that the user has joined.
  406. func (org *User) GetUserTeams(userID int64) error {
  407. teams := make([]*Team, 0, 5)
  408. if err := x.Sql(`SELECT team.* FROM team
  409. INNER JOIN team_user ON team_user.team_id = team.id
  410. WHERE team_user.org_id = ? AND team_user.uid = ?`,
  411. org.Id, userID).Find(&teams); err != nil {
  412. return fmt.Errorf("get teams: %v", err)
  413. }
  414. org.Teams = teams
  415. // FIXME: should I change this value inside method,
  416. // or only in location of caller where it's really needed?
  417. org.NumTeams = len(org.Teams)
  418. return nil
  419. }