You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

872 lines
22 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
8 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "os"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/structs"
  13. "github.com/unknwon/com"
  14. "xorm.io/builder"
  15. "xorm.io/xorm"
  16. )
  17. // IsOwnedBy returns true if given user is in the owner team.
  18. func (org *User) IsOwnedBy(uid int64) (bool, error) {
  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, error) {
  23. return IsOrganizationMember(org.ID, uid)
  24. }
  25. // CanCreateOrgRepo returns true if given user can create repo in organization
  26. func (org *User) CanCreateOrgRepo(uid int64) (bool, error) {
  27. return CanCreateOrgRepo(org.ID, uid)
  28. }
  29. func (org *User) getTeam(e Engine, name string) (*Team, error) {
  30. return getTeam(e, org.ID, name)
  31. }
  32. // GetTeam returns named team of organization.
  33. func (org *User) GetTeam(name string) (*Team, error) {
  34. return org.getTeam(x, name)
  35. }
  36. func (org *User) getOwnerTeam(e Engine) (*Team, error) {
  37. return org.getTeam(e, ownerTeamName)
  38. }
  39. // GetOwnerTeam returns owner team of organization.
  40. func (org *User) GetOwnerTeam() (*Team, error) {
  41. return org.getOwnerTeam(x)
  42. }
  43. func (org *User) getTeams(e Engine) error {
  44. if org.Teams != nil {
  45. return nil
  46. }
  47. return e.
  48. Where("org_id=?", org.ID).
  49. OrderBy("CASE WHEN name LIKE '" + ownerTeamName + "' THEN '' ELSE name END").
  50. Find(&org.Teams)
  51. }
  52. // GetTeams returns all teams that belong to organization.
  53. func (org *User) GetTeams() error {
  54. return org.getTeams(x)
  55. }
  56. // GetMembers returns all members of organization.
  57. func (org *User) GetMembers() (err error) {
  58. org.Members, org.MembersIsPublic, err = FindOrgMembers(FindOrgMembersOpts{
  59. OrgID: org.ID,
  60. })
  61. return
  62. }
  63. // FindOrgMembersOpts represensts find org members condtions
  64. type FindOrgMembersOpts struct {
  65. OrgID int64
  66. PublicOnly bool
  67. Start int
  68. Limit int
  69. }
  70. // CountOrgMembers counts the organization's members
  71. func CountOrgMembers(opts FindOrgMembersOpts) (int64, error) {
  72. sess := x.Where("org_id=?", opts.OrgID)
  73. if opts.PublicOnly {
  74. sess.And("is_public = ?", true)
  75. }
  76. return sess.Count(new(OrgUser))
  77. }
  78. // FindOrgMembers loads organization members according conditions
  79. func FindOrgMembers(opts FindOrgMembersOpts) (UserList, map[int64]bool, error) {
  80. ous, err := GetOrgUsersByOrgID(opts.OrgID, opts.PublicOnly, opts.Start, opts.Limit)
  81. if err != nil {
  82. return nil, nil, err
  83. }
  84. var ids = make([]int64, len(ous))
  85. var idsIsPublic = make(map[int64]bool, len(ous))
  86. for i, ou := range ous {
  87. ids[i] = ou.UID
  88. idsIsPublic[ou.UID] = ou.IsPublic
  89. }
  90. users, err := GetUsersByIDs(ids)
  91. if err != nil {
  92. return nil, nil, err
  93. }
  94. return users, idsIsPublic, nil
  95. }
  96. // AddMember adds new member to organization.
  97. func (org *User) AddMember(uid int64) error {
  98. return AddOrgUser(org.ID, uid)
  99. }
  100. // RemoveMember removes member from organization.
  101. func (org *User) RemoveMember(uid int64) error {
  102. return RemoveOrgUser(org.ID, uid)
  103. }
  104. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  105. return removeOrgRepo(e, org.ID, repoID)
  106. }
  107. // RemoveOrgRepo removes all team-repository relations of organization.
  108. func (org *User) RemoveOrgRepo(repoID int64) error {
  109. return org.removeOrgRepo(x, repoID)
  110. }
  111. // CreateOrganization creates record of a new organization.
  112. func CreateOrganization(org, owner *User) (err error) {
  113. if !owner.CanCreateOrganization() {
  114. return ErrUserNotAllowedCreateOrg{}
  115. }
  116. if err = IsUsableUsername(org.Name); err != nil {
  117. return err
  118. }
  119. isExist, err := IsUserExist(0, org.Name)
  120. if err != nil {
  121. return err
  122. } else if isExist {
  123. return ErrUserAlreadyExist{org.Name}
  124. }
  125. org.LowerName = strings.ToLower(org.Name)
  126. if org.Rands, err = GetUserSalt(); err != nil {
  127. return err
  128. }
  129. if org.Salt, err = GetUserSalt(); err != nil {
  130. return err
  131. }
  132. org.UseCustomAvatar = true
  133. org.MaxRepoCreation = -1
  134. org.NumTeams = 1
  135. org.NumMembers = 1
  136. org.Type = UserTypeOrganization
  137. sess := x.NewSession()
  138. defer sess.Close()
  139. if err = sess.Begin(); err != nil {
  140. return err
  141. }
  142. if _, err = sess.Insert(org); err != nil {
  143. return fmt.Errorf("insert organization: %v", err)
  144. }
  145. if err = org.generateRandomAvatar(sess); err != nil {
  146. return fmt.Errorf("generate random avatar: %v", err)
  147. }
  148. // Add initial creator to organization and owner team.
  149. if _, err = sess.Insert(&OrgUser{
  150. UID: owner.ID,
  151. OrgID: org.ID,
  152. }); err != nil {
  153. return fmt.Errorf("insert org-user relation: %v", err)
  154. }
  155. // Create default owner team.
  156. t := &Team{
  157. OrgID: org.ID,
  158. LowerName: strings.ToLower(ownerTeamName),
  159. Name: ownerTeamName,
  160. Authorize: AccessModeOwner,
  161. NumMembers: 1,
  162. IncludesAllRepositories: true,
  163. CanCreateOrgRepo: true,
  164. }
  165. if _, err = sess.Insert(t); err != nil {
  166. return fmt.Errorf("insert owner team: %v", err)
  167. }
  168. // insert units for team
  169. var units = make([]TeamUnit, 0, len(AllRepoUnitTypes))
  170. for _, tp := range AllRepoUnitTypes {
  171. units = append(units, TeamUnit{
  172. OrgID: org.ID,
  173. TeamID: t.ID,
  174. Type: tp,
  175. })
  176. }
  177. if _, err = sess.Insert(&units); err != nil {
  178. if err := sess.Rollback(); err != nil {
  179. log.Error("CreateOrganization: sess.Rollback: %v", err)
  180. }
  181. return err
  182. }
  183. if _, err = sess.Insert(&TeamUser{
  184. UID: owner.ID,
  185. OrgID: org.ID,
  186. TeamID: t.ID,
  187. }); err != nil {
  188. return fmt.Errorf("insert team-user relation: %v", err)
  189. }
  190. return sess.Commit()
  191. }
  192. // GetOrgByName returns organization by given name.
  193. func GetOrgByName(name string) (*User, error) {
  194. if len(name) == 0 {
  195. return nil, ErrOrgNotExist{0, name}
  196. }
  197. u := &User{
  198. LowerName: strings.ToLower(name),
  199. Type: UserTypeOrganization,
  200. }
  201. has, err := x.Get(u)
  202. if err != nil {
  203. return nil, err
  204. } else if !has {
  205. return nil, ErrOrgNotExist{0, name}
  206. }
  207. return u, nil
  208. }
  209. // CountOrganizations returns number of organizations.
  210. func CountOrganizations() int64 {
  211. count, _ := x.
  212. Where("type=1").
  213. Count(new(User))
  214. return count
  215. }
  216. // DeleteOrganization completely and permanently deletes everything of organization.
  217. func DeleteOrganization(org *User) (err error) {
  218. sess := x.NewSession()
  219. defer sess.Close()
  220. if err = sess.Begin(); err != nil {
  221. return err
  222. }
  223. if err = deleteOrg(sess, org); err != nil {
  224. if IsErrUserOwnRepos(err) {
  225. return err
  226. } else if err != nil {
  227. return fmt.Errorf("deleteOrg: %v", err)
  228. }
  229. }
  230. return sess.Commit()
  231. }
  232. func deleteOrg(e *xorm.Session, u *User) error {
  233. if !u.IsOrganization() {
  234. return fmt.Errorf("You can't delete none organization user: %s", u.Name)
  235. }
  236. // Check ownership of repository.
  237. count, err := getRepositoryCount(e, u)
  238. if err != nil {
  239. return fmt.Errorf("GetRepositoryCount: %v", err)
  240. } else if count > 0 {
  241. return ErrUserOwnRepos{UID: u.ID}
  242. }
  243. if err := deleteBeans(e,
  244. &Team{OrgID: u.ID},
  245. &OrgUser{OrgID: u.ID},
  246. &TeamUser{OrgID: u.ID},
  247. &TeamUnit{OrgID: u.ID},
  248. ); err != nil {
  249. return fmt.Errorf("deleteBeans: %v", err)
  250. }
  251. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  252. return fmt.Errorf("Delete: %v", err)
  253. }
  254. // FIXME: system notice
  255. // Note: There are something just cannot be roll back,
  256. // so just keep error logs of those operations.
  257. path := UserPath(u.Name)
  258. if err := os.RemoveAll(path); err != nil {
  259. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  260. }
  261. if len(u.Avatar) > 0 {
  262. avatarPath := u.CustomAvatarPath()
  263. if com.IsExist(avatarPath) {
  264. if err := os.Remove(avatarPath); err != nil {
  265. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  266. }
  267. }
  268. }
  269. return nil
  270. }
  271. // ________ ____ ___
  272. // \_____ \_______ ____ | | \______ ___________
  273. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  274. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  275. // \_______ /__| \___ /|______//____ >\___ >__|
  276. // \/ /_____/ \/ \/
  277. // OrgUser represents an organization-user relation.
  278. type OrgUser struct {
  279. ID int64 `xorm:"pk autoincr"`
  280. UID int64 `xorm:"INDEX UNIQUE(s)"`
  281. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  282. IsPublic bool `xorm:"INDEX"`
  283. }
  284. func isOrganizationOwner(e Engine, orgID, uid int64) (bool, error) {
  285. ownerTeam, err := getOwnerTeam(e, orgID)
  286. if err != nil {
  287. if IsErrTeamNotExist(err) {
  288. log.Error("Organization does not have owner team: %d", orgID)
  289. return false, nil
  290. }
  291. return false, err
  292. }
  293. return isTeamMember(e, orgID, ownerTeam.ID, uid)
  294. }
  295. // IsOrganizationOwner returns true if given user is in the owner team.
  296. func IsOrganizationOwner(orgID, uid int64) (bool, error) {
  297. return isOrganizationOwner(x, orgID, uid)
  298. }
  299. // IsOrganizationMember returns true if given user is member of organization.
  300. func IsOrganizationMember(orgID, uid int64) (bool, error) {
  301. return isOrganizationMember(x, orgID, uid)
  302. }
  303. func isOrganizationMember(e Engine, orgID, uid int64) (bool, error) {
  304. return e.
  305. Where("uid=?", uid).
  306. And("org_id=?", orgID).
  307. Table("org_user").
  308. Exist()
  309. }
  310. // IsPublicMembership returns true if given user public his/her membership.
  311. func IsPublicMembership(orgID, uid int64) (bool, error) {
  312. return x.
  313. Where("uid=?", uid).
  314. And("org_id=?", orgID).
  315. And("is_public=?", true).
  316. Table("org_user").
  317. Exist()
  318. }
  319. // CanCreateOrgRepo returns true if user can create repo in organization
  320. func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
  321. if owner, err := IsOrganizationOwner(orgID, uid); owner || err != nil {
  322. return owner, err
  323. }
  324. return x.
  325. Where(builder.Eq{"team.can_create_org_repo": true}).
  326. Join("INNER", "team_user", "team_user.team_id = team.id").
  327. And("team_user.uid = ?", uid).
  328. And("team_user.org_id = ?", orgID).
  329. Exist(new(Team))
  330. }
  331. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  332. orgs := make([]*User, 0, 10)
  333. if !showAll {
  334. sess.And("`org_user`.is_public=?", true)
  335. }
  336. return orgs, sess.
  337. And("`org_user`.uid=?", userID).
  338. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").
  339. Asc("`user`.name").
  340. Find(&orgs)
  341. }
  342. // GetOrgsByUserID returns a list of organizations that the given user ID
  343. // has joined.
  344. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  345. sess := x.NewSession()
  346. defer sess.Close()
  347. return getOrgsByUserID(sess, userID, showAll)
  348. }
  349. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  350. orgs := make([]*User, 0, 10)
  351. return orgs, sess.
  352. Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id").
  353. Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
  354. Where("`team_user`.uid=?", userID).
  355. And("`team`.authorize=?", AccessModeOwner).
  356. Asc("`user`.name").
  357. Find(&orgs)
  358. }
  359. // HasOrgVisible tells if the given user can see the given org
  360. func HasOrgVisible(org *User, user *User) bool {
  361. return hasOrgVisible(x, org, user)
  362. }
  363. func hasOrgVisible(e Engine, org *User, user *User) bool {
  364. // Not SignedUser
  365. if user == nil {
  366. return org.Visibility == structs.VisibleTypePublic
  367. }
  368. if user.IsAdmin {
  369. return true
  370. }
  371. if (org.Visibility == structs.VisibleTypePrivate || user.IsRestricted) && !org.isUserPartOfOrg(e, user.ID) {
  372. return false
  373. }
  374. return true
  375. }
  376. // HasOrgsVisible tells if the given user can see at least one of the orgs provided
  377. func HasOrgsVisible(orgs []*User, user *User) bool {
  378. if len(orgs) == 0 {
  379. return false
  380. }
  381. for _, org := range orgs {
  382. if HasOrgVisible(org, user) {
  383. return true
  384. }
  385. }
  386. return false
  387. }
  388. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  389. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  390. sess := x.NewSession()
  391. defer sess.Close()
  392. return getOwnedOrgsByUserID(sess, userID)
  393. }
  394. // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
  395. // given user ID, ordered descending by the given condition.
  396. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  397. return getOwnedOrgsByUserID(x.Desc(desc), userID)
  398. }
  399. // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
  400. // are allowed to create repos.
  401. func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) {
  402. orgs := make([]*User, 0, 10)
  403. return orgs, x.Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id").
  404. Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
  405. Where("`team_user`.uid=?", userID).
  406. And(builder.Eq{"`team`.authorize": AccessModeOwner}.Or(builder.Eq{"`team`.can_create_org_repo": true})).
  407. Desc("`user`.updated_unix").
  408. Find(&orgs)
  409. }
  410. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  411. func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
  412. ous := make([]*OrgUser, 0, 10)
  413. sess := x.
  414. Join("LEFT", "`user`", "`org_user`.org_id=`user`.id").
  415. Where("`org_user`.uid=?", uid)
  416. if !all {
  417. // Only show public organizations
  418. sess.And("is_public=?", true)
  419. }
  420. err := sess.
  421. Asc("`user`.name").
  422. Find(&ous)
  423. return ous, err
  424. }
  425. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  426. func GetOrgUsersByOrgID(orgID int64, publicOnly bool, start, limit int) ([]*OrgUser, error) {
  427. return getOrgUsersByOrgID(x, orgID, publicOnly, start, limit)
  428. }
  429. func getOrgUsersByOrgID(e Engine, orgID int64, publicOnly bool, start, limit int) ([]*OrgUser, error) {
  430. ous := make([]*OrgUser, 0, 10)
  431. sess := e.Where("org_id=?", orgID)
  432. if publicOnly {
  433. sess.And("is_public = ?", true)
  434. }
  435. if limit > 0 {
  436. sess.Limit(limit, start)
  437. }
  438. err := sess.Find(&ous)
  439. return ous, err
  440. }
  441. // ChangeOrgUserStatus changes public or private membership status.
  442. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  443. ou := new(OrgUser)
  444. has, err := x.
  445. Where("uid=?", uid).
  446. And("org_id=?", orgID).
  447. Get(ou)
  448. if err != nil {
  449. return err
  450. } else if !has {
  451. return nil
  452. }
  453. ou.IsPublic = public
  454. _, err = x.ID(ou.ID).Cols("is_public").Update(ou)
  455. return err
  456. }
  457. // AddOrgUser adds new user to given organization.
  458. func AddOrgUser(orgID, uid int64) error {
  459. isAlreadyMember, err := IsOrganizationMember(orgID, uid)
  460. if err != nil || isAlreadyMember {
  461. return err
  462. }
  463. sess := x.NewSession()
  464. defer sess.Close()
  465. if err := sess.Begin(); err != nil {
  466. return err
  467. }
  468. ou := &OrgUser{
  469. UID: uid,
  470. OrgID: orgID,
  471. IsPublic: setting.Service.DefaultOrgMemberVisible,
  472. }
  473. if _, err := sess.Insert(ou); err != nil {
  474. if err := sess.Rollback(); err != nil {
  475. log.Error("AddOrgUser: sess.Rollback: %v", err)
  476. }
  477. return err
  478. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  479. if err := sess.Rollback(); err != nil {
  480. log.Error("AddOrgUser: sess.Rollback: %v", err)
  481. }
  482. return err
  483. }
  484. return sess.Commit()
  485. }
  486. func removeOrgUser(sess *xorm.Session, orgID, userID int64) error {
  487. ou := new(OrgUser)
  488. has, err := sess.
  489. Where("uid=?", userID).
  490. And("org_id=?", orgID).
  491. Get(ou)
  492. if err != nil {
  493. return fmt.Errorf("get org-user: %v", err)
  494. } else if !has {
  495. return nil
  496. }
  497. org, err := getUserByID(sess, orgID)
  498. if err != nil {
  499. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  500. }
  501. // Check if the user to delete is the last member in owner team.
  502. if isOwner, err := isOrganizationOwner(sess, orgID, userID); err != nil {
  503. return err
  504. } else if isOwner {
  505. t, err := org.getOwnerTeam(sess)
  506. if err != nil {
  507. return err
  508. }
  509. if t.NumMembers == 1 {
  510. if err := t.getMembers(sess); err != nil {
  511. return err
  512. }
  513. if t.Members[0].ID == userID {
  514. return ErrLastOrgOwner{UID: userID}
  515. }
  516. }
  517. }
  518. if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
  519. return err
  520. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  521. return err
  522. }
  523. // Delete all repository accesses and unwatch them.
  524. env, err := org.accessibleReposEnv(sess, userID)
  525. if err != nil {
  526. return fmt.Errorf("AccessibleReposEnv: %v", err)
  527. }
  528. repoIDs, err := env.RepoIDs(1, org.NumRepos)
  529. if err != nil {
  530. return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err)
  531. }
  532. for _, repoID := range repoIDs {
  533. if err = watchRepo(sess, userID, repoID, false); err != nil {
  534. return err
  535. }
  536. }
  537. if len(repoIDs) > 0 {
  538. if _, err = sess.
  539. Where("user_id = ?", userID).
  540. In("repo_id", repoIDs).
  541. Delete(new(Access)); err != nil {
  542. return err
  543. }
  544. }
  545. // Delete member in his/her teams.
  546. teams, err := getUserOrgTeams(sess, org.ID, userID)
  547. if err != nil {
  548. return err
  549. }
  550. for _, t := range teams {
  551. if err = removeTeamMember(sess, t, userID); err != nil {
  552. return err
  553. }
  554. }
  555. return nil
  556. }
  557. // RemoveOrgUser removes user from given organization.
  558. func RemoveOrgUser(orgID, userID int64) error {
  559. sess := x.NewSession()
  560. defer sess.Close()
  561. if err := sess.Begin(); err != nil {
  562. return err
  563. }
  564. if err := removeOrgUser(sess, orgID, userID); err != nil {
  565. return err
  566. }
  567. return sess.Commit()
  568. }
  569. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  570. teamRepos := make([]*TeamRepo, 0, 10)
  571. if err := e.Find(&teamRepos, &TeamRepo{OrgID: orgID, RepoID: repoID}); err != nil {
  572. return err
  573. }
  574. if len(teamRepos) == 0 {
  575. return nil
  576. }
  577. if _, err := e.Delete(&TeamRepo{
  578. OrgID: orgID,
  579. RepoID: repoID,
  580. }); err != nil {
  581. return err
  582. }
  583. teamIDs := make([]int64, len(teamRepos))
  584. for i, teamRepo := range teamRepos {
  585. teamIDs[i] = teamRepo.TeamID
  586. }
  587. _, err := e.Decr("num_repos").In("id", teamIDs).Update(new(Team))
  588. return err
  589. }
  590. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  591. teams := make([]*Team, 0, org.NumTeams)
  592. return teams, e.
  593. Where("`team_user`.org_id = ?", org.ID).
  594. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  595. Join("INNER", "`user`", "`user`.id=team_user.uid").
  596. And("`team_user`.uid = ?", userID).
  597. Asc("`user`.name").
  598. Cols(cols...).
  599. Find(&teams)
  600. }
  601. func (org *User) getUserTeamIDs(e Engine, userID int64) ([]int64, error) {
  602. teamIDs := make([]int64, 0, org.NumTeams)
  603. return teamIDs, e.
  604. Table("team").
  605. Cols("team.id").
  606. Where("`team_user`.org_id = ?", org.ID).
  607. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  608. And("`team_user`.uid = ?", userID).
  609. Find(&teamIDs)
  610. }
  611. // TeamsWithAccessToRepo returns all teamsthat have given access level to the repository.
  612. func (org *User) TeamsWithAccessToRepo(repoID int64, mode AccessMode) ([]*Team, error) {
  613. return GetTeamsWithAccessToRepo(org.ID, repoID, mode)
  614. }
  615. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
  616. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  617. return org.getUserTeamIDs(x, userID)
  618. }
  619. // GetUserTeams returns all teams that belong to user,
  620. // and that the user has joined.
  621. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  622. return org.getUserTeams(x, userID)
  623. }
  624. // AccessibleReposEnvironment operations involving the repositories that are
  625. // accessible to a particular user
  626. type AccessibleReposEnvironment interface {
  627. CountRepos() (int64, error)
  628. RepoIDs(page, pageSize int) ([]int64, error)
  629. Repos(page, pageSize int) ([]*Repository, error)
  630. MirrorRepos() ([]*Repository, error)
  631. AddKeyword(keyword string)
  632. SetSort(SearchOrderBy)
  633. }
  634. type accessibleReposEnv struct {
  635. org *User
  636. user *User
  637. teamIDs []int64
  638. e Engine
  639. keyword string
  640. orderBy SearchOrderBy
  641. }
  642. // AccessibleReposEnv an AccessibleReposEnvironment for the repositories in `org`
  643. // that are accessible to the specified user.
  644. func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) {
  645. return org.accessibleReposEnv(x, userID)
  646. }
  647. func (org *User) accessibleReposEnv(e Engine, userID int64) (AccessibleReposEnvironment, error) {
  648. var user *User
  649. if userID > 0 {
  650. u, err := getUserByID(e, userID)
  651. if err != nil {
  652. return nil, err
  653. }
  654. user = u
  655. }
  656. teamIDs, err := org.getUserTeamIDs(e, userID)
  657. if err != nil {
  658. return nil, err
  659. }
  660. return &accessibleReposEnv{
  661. org: org,
  662. user: user,
  663. teamIDs: teamIDs,
  664. e: e,
  665. orderBy: SearchOrderByRecentUpdated,
  666. }, nil
  667. }
  668. func (env *accessibleReposEnv) cond() builder.Cond {
  669. var cond = builder.NewCond()
  670. if env.user == nil || !env.user.IsRestricted {
  671. cond = cond.Or(builder.Eq{
  672. "`repository`.owner_id": env.org.ID,
  673. "`repository`.is_private": false,
  674. })
  675. }
  676. if len(env.teamIDs) > 0 {
  677. cond = cond.Or(builder.In("team_repo.team_id", env.teamIDs))
  678. }
  679. if env.keyword != "" {
  680. cond = cond.And(builder.Like{"`repository`.lower_name", strings.ToLower(env.keyword)})
  681. }
  682. return cond
  683. }
  684. func (env *accessibleReposEnv) CountRepos() (int64, error) {
  685. repoCount, err := env.e.
  686. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  687. Where(env.cond()).
  688. Distinct("`repository`.id").
  689. Count(&Repository{})
  690. if err != nil {
  691. return 0, fmt.Errorf("count user repositories in organization: %v", err)
  692. }
  693. return repoCount, nil
  694. }
  695. func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
  696. if page <= 0 {
  697. page = 1
  698. }
  699. repoIDs := make([]int64, 0, pageSize)
  700. return repoIDs, env.e.
  701. Table("repository").
  702. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  703. Where(env.cond()).
  704. GroupBy("`repository`.id,`repository`."+strings.Fields(string(env.orderBy))[0]).
  705. OrderBy(string(env.orderBy)).
  706. Limit(pageSize, (page-1)*pageSize).
  707. Cols("`repository`.id").
  708. Find(&repoIDs)
  709. }
  710. func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*Repository, error) {
  711. repoIDs, err := env.RepoIDs(page, pageSize)
  712. if err != nil {
  713. return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err)
  714. }
  715. repos := make([]*Repository, 0, len(repoIDs))
  716. if len(repoIDs) == 0 {
  717. return repos, nil
  718. }
  719. return repos, env.e.
  720. In("`repository`.id", repoIDs).
  721. OrderBy(string(env.orderBy)).
  722. Find(&repos)
  723. }
  724. func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) {
  725. repoIDs := make([]int64, 0, 10)
  726. return repoIDs, env.e.
  727. Table("repository").
  728. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true).
  729. Where(env.cond()).
  730. GroupBy("`repository`.id, `repository`.updated_unix").
  731. OrderBy(string(env.orderBy)).
  732. Cols("`repository`.id").
  733. Find(&repoIDs)
  734. }
  735. func (env *accessibleReposEnv) MirrorRepos() ([]*Repository, error) {
  736. repoIDs, err := env.MirrorRepoIDs()
  737. if err != nil {
  738. return nil, fmt.Errorf("MirrorRepoIDs: %v", err)
  739. }
  740. repos := make([]*Repository, 0, len(repoIDs))
  741. if len(repoIDs) == 0 {
  742. return repos, nil
  743. }
  744. return repos, env.e.
  745. In("`repository`.id", repoIDs).
  746. Find(&repos)
  747. }
  748. func (env *accessibleReposEnv) AddKeyword(keyword string) {
  749. env.keyword = keyword
  750. }
  751. func (env *accessibleReposEnv) SetSort(orderBy SearchOrderBy) {
  752. env.orderBy = orderBy
  753. }