A fork of Gitea (see branch `mj`) adding Majority Judgment Polls 𐄷 over Issues and Merge Requests. https://git.mieuxvoter.fr
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.

916 lines
24 KiB

API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
8 years ago
8 years ago
6 years ago
7 years ago
7 years ago
7 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
3 years ago
6 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>
3 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>
3 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>
3 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. "strings"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/storage"
  12. "code.gitea.io/gitea/modules/structs"
  13. "code.gitea.io/gitea/modules/util"
  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 paginated teams that belong to organization.
  53. func (org *User) GetTeams(opts *SearchTeamOptions) error {
  54. if opts.Page != 0 {
  55. return org.getTeams(opts.getPaginatedSession())
  56. }
  57. return org.getTeams(x)
  58. }
  59. // GetMembers returns all members of organization.
  60. func (org *User) GetMembers() (err error) {
  61. org.Members, org.MembersIsPublic, err = FindOrgMembers(&FindOrgMembersOpts{
  62. OrgID: org.ID,
  63. })
  64. return
  65. }
  66. // FindOrgMembersOpts represensts find org members condtions
  67. type FindOrgMembersOpts struct {
  68. ListOptions
  69. OrgID int64
  70. PublicOnly bool
  71. }
  72. // CountOrgMembers counts the organization's members
  73. func CountOrgMembers(opts FindOrgMembersOpts) (int64, error) {
  74. sess := x.Where("org_id=?", opts.OrgID)
  75. if opts.PublicOnly {
  76. sess.And("is_public = ?", true)
  77. }
  78. return sess.Count(new(OrgUser))
  79. }
  80. // FindOrgMembers loads organization members according conditions
  81. func FindOrgMembers(opts *FindOrgMembersOpts) (UserList, map[int64]bool, error) {
  82. ous, err := GetOrgUsersByOrgID(opts)
  83. if err != nil {
  84. return nil, nil, err
  85. }
  86. ids := make([]int64, len(ous))
  87. idsIsPublic := make(map[int64]bool, len(ous))
  88. for i, ou := range ous {
  89. ids[i] = ou.UID
  90. idsIsPublic[ou.UID] = ou.IsPublic
  91. }
  92. users, err := GetUsersByIDs(ids)
  93. if err != nil {
  94. return nil, nil, err
  95. }
  96. return users, idsIsPublic, nil
  97. }
  98. // AddMember adds new member to organization.
  99. func (org *User) AddMember(uid int64) error {
  100. return AddOrgUser(org.ID, uid)
  101. }
  102. // RemoveMember removes member from organization.
  103. func (org *User) RemoveMember(uid int64) error {
  104. return RemoveOrgUser(org.ID, uid)
  105. }
  106. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  107. return removeOrgRepo(e, org.ID, repoID)
  108. }
  109. // RemoveOrgRepo removes all team-repository relations of organization.
  110. func (org *User) RemoveOrgRepo(repoID int64) error {
  111. return org.removeOrgRepo(x, repoID)
  112. }
  113. // CreateOrganization creates record of a new organization.
  114. func CreateOrganization(org, owner *User) (err error) {
  115. if !owner.CanCreateOrganization() {
  116. return ErrUserNotAllowedCreateOrg{}
  117. }
  118. if err = IsUsableUsername(org.Name); err != nil {
  119. return err
  120. }
  121. isExist, err := IsUserExist(0, org.Name)
  122. if err != nil {
  123. return err
  124. } else if isExist {
  125. return ErrUserAlreadyExist{org.Name}
  126. }
  127. org.LowerName = strings.ToLower(org.Name)
  128. if org.Rands, err = GetUserSalt(); err != nil {
  129. return err
  130. }
  131. if org.Salt, err = GetUserSalt(); err != nil {
  132. return err
  133. }
  134. org.UseCustomAvatar = true
  135. org.MaxRepoCreation = -1
  136. org.NumTeams = 1
  137. org.NumMembers = 1
  138. org.Type = UserTypeOrganization
  139. sess := x.NewSession()
  140. defer sess.Close()
  141. if err = sess.Begin(); err != nil {
  142. return err
  143. }
  144. if err = deleteUserRedirect(sess, org.Name); err != nil {
  145. return err
  146. }
  147. if _, err = sess.Insert(org); err != nil {
  148. return fmt.Errorf("insert organization: %v", err)
  149. }
  150. if err = org.generateRandomAvatar(sess); err != nil {
  151. return fmt.Errorf("generate random avatar: %v", err)
  152. }
  153. // Add initial creator to organization and owner team.
  154. if _, err = sess.Insert(&OrgUser{
  155. UID: owner.ID,
  156. OrgID: org.ID,
  157. }); err != nil {
  158. return fmt.Errorf("insert org-user relation: %v", err)
  159. }
  160. // Create default owner team.
  161. t := &Team{
  162. OrgID: org.ID,
  163. LowerName: strings.ToLower(ownerTeamName),
  164. Name: ownerTeamName,
  165. Authorize: AccessModeOwner,
  166. NumMembers: 1,
  167. IncludesAllRepositories: true,
  168. CanCreateOrgRepo: true,
  169. }
  170. if _, err = sess.Insert(t); err != nil {
  171. return fmt.Errorf("insert owner team: %v", err)
  172. }
  173. // insert units for team
  174. units := make([]TeamUnit, 0, len(AllRepoUnitTypes))
  175. for _, tp := range AllRepoUnitTypes {
  176. units = append(units, TeamUnit{
  177. OrgID: org.ID,
  178. TeamID: t.ID,
  179. Type: tp,
  180. })
  181. }
  182. if _, err = sess.Insert(&units); err != nil {
  183. if err := sess.Rollback(); err != nil {
  184. log.Error("CreateOrganization: sess.Rollback: %v", err)
  185. }
  186. return err
  187. }
  188. if _, err = sess.Insert(&TeamUser{
  189. UID: owner.ID,
  190. OrgID: org.ID,
  191. TeamID: t.ID,
  192. }); err != nil {
  193. return fmt.Errorf("insert team-user relation: %v", err)
  194. }
  195. return sess.Commit()
  196. }
  197. // GetOrgByName returns organization by given name.
  198. func GetOrgByName(name string) (*User, error) {
  199. if len(name) == 0 {
  200. return nil, ErrOrgNotExist{0, name}
  201. }
  202. u := &User{
  203. LowerName: strings.ToLower(name),
  204. Type: UserTypeOrganization,
  205. }
  206. has, err := x.Get(u)
  207. if err != nil {
  208. return nil, err
  209. } else if !has {
  210. return nil, ErrOrgNotExist{0, name}
  211. }
  212. return u, nil
  213. }
  214. // CountOrganizations returns number of organizations.
  215. func CountOrganizations() int64 {
  216. count, _ := x.
  217. Where("type=1").
  218. Count(new(User))
  219. return count
  220. }
  221. // DeleteOrganization completely and permanently deletes everything of organization.
  222. func DeleteOrganization(org *User) (err error) {
  223. if !org.IsOrganization() {
  224. return fmt.Errorf("%s is a user not an organization", org.Name)
  225. }
  226. sess := x.NewSession()
  227. defer sess.Close()
  228. if err = sess.Begin(); err != nil {
  229. return err
  230. }
  231. if err = deleteOrg(sess, org); err != nil {
  232. if IsErrUserOwnRepos(err) {
  233. return err
  234. } else if err != nil {
  235. return fmt.Errorf("deleteOrg: %v", err)
  236. }
  237. }
  238. return sess.Commit()
  239. }
  240. func deleteOrg(e *xorm.Session, u *User) error {
  241. // Check ownership of repository.
  242. count, err := getRepositoryCount(e, u)
  243. if err != nil {
  244. return fmt.Errorf("GetRepositoryCount: %v", err)
  245. } else if count > 0 {
  246. return ErrUserOwnRepos{UID: u.ID}
  247. }
  248. if err := deleteBeans(e,
  249. &Team{OrgID: u.ID},
  250. &OrgUser{OrgID: u.ID},
  251. &TeamUser{OrgID: u.ID},
  252. &TeamUnit{OrgID: u.ID},
  253. ); err != nil {
  254. return fmt.Errorf("deleteBeans: %v", err)
  255. }
  256. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  257. return fmt.Errorf("Delete: %v", err)
  258. }
  259. // FIXME: system notice
  260. // Note: There are something just cannot be roll back,
  261. // so just keep error logs of those operations.
  262. path := UserPath(u.Name)
  263. if err := util.RemoveAll(path); err != nil {
  264. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  265. }
  266. if len(u.Avatar) > 0 {
  267. avatarPath := u.CustomAvatarRelativePath()
  268. if err := storage.Avatars.Delete(avatarPath); err != nil {
  269. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  270. }
  271. }
  272. return nil
  273. }
  274. // ________ ____ ___
  275. // \_____ \_______ ____ | | \______ ___________
  276. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  277. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  278. // \_______ /__| \___ /|______//____ >\___ >__|
  279. // \/ /_____/ \/ \/
  280. // OrgUser represents an organization-user relation.
  281. type OrgUser struct {
  282. ID int64 `xorm:"pk autoincr"`
  283. UID int64 `xorm:"INDEX UNIQUE(s)"`
  284. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  285. IsPublic bool `xorm:"INDEX"`
  286. }
  287. func isOrganizationOwner(e Engine, orgID, uid int64) (bool, error) {
  288. ownerTeam, err := getOwnerTeam(e, orgID)
  289. if err != nil {
  290. if IsErrTeamNotExist(err) {
  291. log.Error("Organization does not have owner team: %d", orgID)
  292. return false, nil
  293. }
  294. return false, err
  295. }
  296. return isTeamMember(e, orgID, ownerTeam.ID, uid)
  297. }
  298. // IsOrganizationOwner returns true if given user is in the owner team.
  299. func IsOrganizationOwner(orgID, uid int64) (bool, error) {
  300. return isOrganizationOwner(x, orgID, uid)
  301. }
  302. // IsOrganizationMember returns true if given user is member of organization.
  303. func IsOrganizationMember(orgID, uid int64) (bool, error) {
  304. return isOrganizationMember(x, orgID, uid)
  305. }
  306. func isOrganizationMember(e Engine, orgID, uid int64) (bool, error) {
  307. return e.
  308. Where("uid=?", uid).
  309. And("org_id=?", orgID).
  310. Table("org_user").
  311. Exist()
  312. }
  313. // IsPublicMembership returns true if given user public his/her membership.
  314. func IsPublicMembership(orgID, uid int64) (bool, error) {
  315. return x.
  316. Where("uid=?", uid).
  317. And("org_id=?", orgID).
  318. And("is_public=?", true).
  319. Table("org_user").
  320. Exist()
  321. }
  322. // CanCreateOrgRepo returns true if user can create repo in organization
  323. func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
  324. if owner, err := IsOrganizationOwner(orgID, uid); owner || err != nil {
  325. return owner, err
  326. }
  327. return x.
  328. Where(builder.Eq{"team.can_create_org_repo": true}).
  329. Join("INNER", "team_user", "team_user.team_id = team.id").
  330. And("team_user.uid = ?", uid).
  331. And("team_user.org_id = ?", orgID).
  332. Exist(new(Team))
  333. }
  334. // GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization
  335. func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) {
  336. return getUsersWhoCanCreateOrgRepo(x, orgID)
  337. }
  338. func getUsersWhoCanCreateOrgRepo(e Engine, orgID int64) ([]*User, error) {
  339. users := make([]*User, 0, 10)
  340. return users, x.
  341. Join("INNER", "`team_user`", "`team_user`.uid=`user`.id").
  342. Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
  343. Where(builder.Eq{"team.can_create_org_repo": true}.Or(builder.Eq{"team.authorize": AccessModeOwner})).
  344. And("team_user.org_id = ?", orgID).Asc("`user`.name").Find(&users)
  345. }
  346. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  347. orgs := make([]*User, 0, 10)
  348. if !showAll {
  349. sess.And("`org_user`.is_public=?", true)
  350. }
  351. return orgs, sess.
  352. And("`org_user`.uid=?", userID).
  353. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").
  354. Asc("`user`.name").
  355. Find(&orgs)
  356. }
  357. // GetOrgsByUserID returns a list of organizations that the given user ID
  358. // has joined.
  359. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  360. sess := x.NewSession()
  361. defer sess.Close()
  362. return getOrgsByUserID(sess, userID, showAll)
  363. }
  364. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  365. orgs := make([]*User, 0, 10)
  366. return orgs, sess.
  367. Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id").
  368. Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
  369. Where("`team_user`.uid=?", userID).
  370. And("`team`.authorize=?", AccessModeOwner).
  371. Asc("`user`.name").
  372. Find(&orgs)
  373. }
  374. // HasOrgVisible tells if the given user can see the given org
  375. func HasOrgVisible(org, user *User) bool {
  376. return hasOrgVisible(x, org, user)
  377. }
  378. func hasOrgVisible(e Engine, org, user *User) bool {
  379. // Not SignedUser
  380. if user == nil {
  381. return org.Visibility == structs.VisibleTypePublic
  382. }
  383. if user.IsAdmin {
  384. return true
  385. }
  386. if (org.Visibility == structs.VisibleTypePrivate || user.IsRestricted) && !org.hasMemberWithUserID(e, user.ID) {
  387. return false
  388. }
  389. return true
  390. }
  391. // HasOrgsVisible tells if the given user can see at least one of the orgs provided
  392. func HasOrgsVisible(orgs []*User, user *User) bool {
  393. if len(orgs) == 0 {
  394. return false
  395. }
  396. for _, org := range orgs {
  397. if HasOrgVisible(org, user) {
  398. return true
  399. }
  400. }
  401. return false
  402. }
  403. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  404. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  405. sess := x.NewSession()
  406. defer sess.Close()
  407. return getOwnedOrgsByUserID(sess, userID)
  408. }
  409. // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
  410. // given user ID, ordered descending by the given condition.
  411. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  412. return getOwnedOrgsByUserID(x.Desc(desc), userID)
  413. }
  414. // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
  415. // are allowed to create repos.
  416. func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) {
  417. orgs := make([]*User, 0, 10)
  418. return orgs, x.Where(builder.In("id", builder.Select("`user`.id").From("`user`").
  419. Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id").
  420. Join("INNER", "`team`", "`team`.id = `team_user`.team_id").
  421. Where(builder.Eq{"`team_user`.uid": userID}).
  422. And(builder.Eq{"`team`.authorize": AccessModeOwner}.Or(builder.Eq{"`team`.can_create_org_repo": true})))).
  423. Asc("`user`.name").
  424. Find(&orgs)
  425. }
  426. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  427. func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUser, error) {
  428. ous := make([]*OrgUser, 0, 10)
  429. sess := x.
  430. Join("LEFT", "`user`", "`org_user`.org_id=`user`.id").
  431. Where("`org_user`.uid=?", uid)
  432. if !opts.All {
  433. // Only show public organizations
  434. sess.And("is_public=?", true)
  435. }
  436. if opts.PageSize != 0 {
  437. sess = opts.setSessionPagination(sess)
  438. }
  439. err := sess.
  440. Asc("`user`.name").
  441. Find(&ous)
  442. return ous, err
  443. }
  444. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  445. func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) {
  446. return getOrgUsersByOrgID(x, opts)
  447. }
  448. func getOrgUsersByOrgID(e Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) {
  449. sess := e.Where("org_id=?", opts.OrgID)
  450. if opts.PublicOnly {
  451. sess.And("is_public = ?", true)
  452. }
  453. if opts.ListOptions.PageSize > 0 {
  454. sess = opts.setSessionPagination(sess)
  455. ous := make([]*OrgUser, 0, opts.PageSize)
  456. return ous, sess.Find(&ous)
  457. }
  458. var ous []*OrgUser
  459. return ous, sess.Find(&ous)
  460. }
  461. // ChangeOrgUserStatus changes public or private membership status.
  462. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  463. ou := new(OrgUser)
  464. has, err := x.
  465. Where("uid=?", uid).
  466. And("org_id=?", orgID).
  467. Get(ou)
  468. if err != nil {
  469. return err
  470. } else if !has {
  471. return nil
  472. }
  473. ou.IsPublic = public
  474. _, err = x.ID(ou.ID).Cols("is_public").Update(ou)
  475. return err
  476. }
  477. // AddOrgUser adds new user to given organization.
  478. func AddOrgUser(orgID, uid int64) error {
  479. isAlreadyMember, err := IsOrganizationMember(orgID, uid)
  480. if err != nil || isAlreadyMember {
  481. return err
  482. }
  483. sess := x.NewSession()
  484. defer sess.Close()
  485. if err := sess.Begin(); err != nil {
  486. return err
  487. }
  488. ou := &OrgUser{
  489. UID: uid,
  490. OrgID: orgID,
  491. IsPublic: setting.Service.DefaultOrgMemberVisible,
  492. }
  493. if _, err := sess.Insert(ou); err != nil {
  494. if err := sess.Rollback(); err != nil {
  495. log.Error("AddOrgUser: sess.Rollback: %v", err)
  496. }
  497. return err
  498. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  499. if err := sess.Rollback(); err != nil {
  500. log.Error("AddOrgUser: sess.Rollback: %v", err)
  501. }
  502. return err
  503. }
  504. return sess.Commit()
  505. }
  506. func removeOrgUser(sess *xorm.Session, orgID, userID int64) error {
  507. ou := new(OrgUser)
  508. has, err := sess.
  509. Where("uid=?", userID).
  510. And("org_id=?", orgID).
  511. Get(ou)
  512. if err != nil {
  513. return fmt.Errorf("get org-user: %v", err)
  514. } else if !has {
  515. return nil
  516. }
  517. org, err := getUserByID(sess, orgID)
  518. if err != nil {
  519. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  520. }
  521. // Check if the user to delete is the last member in owner team.
  522. if isOwner, err := isOrganizationOwner(sess, orgID, userID); err != nil {
  523. return err
  524. } else if isOwner {
  525. t, err := org.getOwnerTeam(sess)
  526. if err != nil {
  527. return err
  528. }
  529. if t.NumMembers == 1 {
  530. if err := t.getMembers(sess); err != nil {
  531. return err
  532. }
  533. if t.Members[0].ID == userID {
  534. return ErrLastOrgOwner{UID: userID}
  535. }
  536. }
  537. }
  538. if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
  539. return err
  540. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  541. return err
  542. }
  543. // Delete all repository accesses and unwatch them.
  544. env, err := org.accessibleReposEnv(sess, userID)
  545. if err != nil {
  546. return fmt.Errorf("AccessibleReposEnv: %v", err)
  547. }
  548. repoIDs, err := env.RepoIDs(1, org.NumRepos)
  549. if err != nil {
  550. return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err)
  551. }
  552. for _, repoID := range repoIDs {
  553. if err = watchRepo(sess, userID, repoID, false); err != nil {
  554. return err
  555. }
  556. }
  557. if len(repoIDs) > 0 {
  558. if _, err = sess.
  559. Where("user_id = ?", userID).
  560. In("repo_id", repoIDs).
  561. Delete(new(Access)); err != nil {
  562. return err
  563. }
  564. }
  565. // Delete member in his/her teams.
  566. teams, err := getUserOrgTeams(sess, org.ID, userID)
  567. if err != nil {
  568. return err
  569. }
  570. for _, t := range teams {
  571. if err = removeTeamMember(sess, t, userID); err != nil {
  572. return err
  573. }
  574. }
  575. return nil
  576. }
  577. // RemoveOrgUser removes user from given organization.
  578. func RemoveOrgUser(orgID, userID int64) error {
  579. sess := x.NewSession()
  580. defer sess.Close()
  581. if err := sess.Begin(); err != nil {
  582. return err
  583. }
  584. if err := removeOrgUser(sess, orgID, userID); err != nil {
  585. return err
  586. }
  587. return sess.Commit()
  588. }
  589. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  590. teamRepos := make([]*TeamRepo, 0, 10)
  591. if err := e.Find(&teamRepos, &TeamRepo{OrgID: orgID, RepoID: repoID}); err != nil {
  592. return err
  593. }
  594. if len(teamRepos) == 0 {
  595. return nil
  596. }
  597. if _, err := e.Delete(&TeamRepo{
  598. OrgID: orgID,
  599. RepoID: repoID,
  600. }); err != nil {
  601. return err
  602. }
  603. teamIDs := make([]int64, len(teamRepos))
  604. for i, teamRepo := range teamRepos {
  605. teamIDs[i] = teamRepo.TeamID
  606. }
  607. _, err := e.Decr("num_repos").In("id", teamIDs).Update(new(Team))
  608. return err
  609. }
  610. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  611. teams := make([]*Team, 0, org.NumTeams)
  612. return teams, e.
  613. Where("`team_user`.org_id = ?", org.ID).
  614. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  615. Join("INNER", "`user`", "`user`.id=team_user.uid").
  616. And("`team_user`.uid = ?", userID).
  617. Asc("`user`.name").
  618. Cols(cols...).
  619. Find(&teams)
  620. }
  621. func (org *User) getUserTeamIDs(e Engine, userID int64) ([]int64, error) {
  622. teamIDs := make([]int64, 0, org.NumTeams)
  623. return teamIDs, e.
  624. Table("team").
  625. Cols("team.id").
  626. Where("`team_user`.org_id = ?", org.ID).
  627. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  628. And("`team_user`.uid = ?", userID).
  629. Find(&teamIDs)
  630. }
  631. // TeamsWithAccessToRepo returns all teams that have given access level to the repository.
  632. func (org *User) TeamsWithAccessToRepo(repoID int64, mode AccessMode) ([]*Team, error) {
  633. return GetTeamsWithAccessToRepo(org.ID, repoID, mode)
  634. }
  635. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
  636. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  637. return org.getUserTeamIDs(x, userID)
  638. }
  639. // GetUserTeams returns all teams that belong to user,
  640. // and that the user has joined.
  641. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  642. return org.getUserTeams(x, userID)
  643. }
  644. // AccessibleReposEnvironment operations involving the repositories that are
  645. // accessible to a particular user
  646. type AccessibleReposEnvironment interface {
  647. CountRepos() (int64, error)
  648. RepoIDs(page, pageSize int) ([]int64, error)
  649. Repos(page, pageSize int) ([]*Repository, error)
  650. MirrorRepos() ([]*Repository, error)
  651. AddKeyword(keyword string)
  652. SetSort(SearchOrderBy)
  653. }
  654. type accessibleReposEnv struct {
  655. org *User
  656. user *User
  657. team *Team
  658. teamIDs []int64
  659. e Engine
  660. keyword string
  661. orderBy SearchOrderBy
  662. }
  663. // AccessibleReposEnv builds an AccessibleReposEnvironment for the repositories in `org`
  664. // that are accessible to the specified user.
  665. func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) {
  666. return org.accessibleReposEnv(x, userID)
  667. }
  668. func (org *User) accessibleReposEnv(e Engine, userID int64) (AccessibleReposEnvironment, error) {
  669. var user *User
  670. if userID > 0 {
  671. u, err := getUserByID(e, userID)
  672. if err != nil {
  673. return nil, err
  674. }
  675. user = u
  676. }
  677. teamIDs, err := org.getUserTeamIDs(e, userID)
  678. if err != nil {
  679. return nil, err
  680. }
  681. return &accessibleReposEnv{
  682. org: org,
  683. user: user,
  684. teamIDs: teamIDs,
  685. e: e,
  686. orderBy: SearchOrderByRecentUpdated,
  687. }, nil
  688. }
  689. // AccessibleTeamReposEnv an AccessibleReposEnvironment for the repositories in `org`
  690. // that are accessible to the specified team.
  691. func (org *User) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvironment {
  692. return &accessibleReposEnv{
  693. org: org,
  694. team: team,
  695. e: x,
  696. orderBy: SearchOrderByRecentUpdated,
  697. }
  698. }
  699. func (env *accessibleReposEnv) cond() builder.Cond {
  700. cond := builder.NewCond()
  701. if env.team != nil {
  702. cond = cond.And(builder.Eq{"team_repo.team_id": env.team.ID})
  703. } else {
  704. if env.user == nil || !env.user.IsRestricted {
  705. cond = cond.Or(builder.Eq{
  706. "`repository`.owner_id": env.org.ID,
  707. "`repository`.is_private": false,
  708. })
  709. }
  710. if len(env.teamIDs) > 0 {
  711. cond = cond.Or(builder.In("team_repo.team_id", env.teamIDs))
  712. }
  713. }
  714. if env.keyword != "" {
  715. cond = cond.And(builder.Like{"`repository`.lower_name", strings.ToLower(env.keyword)})
  716. }
  717. return cond
  718. }
  719. func (env *accessibleReposEnv) CountRepos() (int64, error) {
  720. repoCount, err := env.e.
  721. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  722. Where(env.cond()).
  723. Distinct("`repository`.id").
  724. Count(&Repository{})
  725. if err != nil {
  726. return 0, fmt.Errorf("count user repositories in organization: %v", err)
  727. }
  728. return repoCount, nil
  729. }
  730. func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
  731. if page <= 0 {
  732. page = 1
  733. }
  734. repoIDs := make([]int64, 0, pageSize)
  735. return repoIDs, env.e.
  736. Table("repository").
  737. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  738. Where(env.cond()).
  739. GroupBy("`repository`.id,`repository`."+strings.Fields(string(env.orderBy))[0]).
  740. OrderBy(string(env.orderBy)).
  741. Limit(pageSize, (page-1)*pageSize).
  742. Cols("`repository`.id").
  743. Find(&repoIDs)
  744. }
  745. func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*Repository, error) {
  746. repoIDs, err := env.RepoIDs(page, pageSize)
  747. if err != nil {
  748. return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err)
  749. }
  750. repos := make([]*Repository, 0, len(repoIDs))
  751. if len(repoIDs) == 0 {
  752. return repos, nil
  753. }
  754. return repos, env.e.
  755. In("`repository`.id", repoIDs).
  756. OrderBy(string(env.orderBy)).
  757. Find(&repos)
  758. }
  759. func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) {
  760. repoIDs := make([]int64, 0, 10)
  761. return repoIDs, env.e.
  762. Table("repository").
  763. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true).
  764. Where(env.cond()).
  765. GroupBy("`repository`.id, `repository`.updated_unix").
  766. OrderBy(string(env.orderBy)).
  767. Cols("`repository`.id").
  768. Find(&repoIDs)
  769. }
  770. func (env *accessibleReposEnv) MirrorRepos() ([]*Repository, error) {
  771. repoIDs, err := env.MirrorRepoIDs()
  772. if err != nil {
  773. return nil, fmt.Errorf("MirrorRepoIDs: %v", err)
  774. }
  775. repos := make([]*Repository, 0, len(repoIDs))
  776. if len(repoIDs) == 0 {
  777. return repos, nil
  778. }
  779. return repos, env.e.
  780. In("`repository`.id", repoIDs).
  781. Find(&repos)
  782. }
  783. func (env *accessibleReposEnv) AddKeyword(keyword string) {
  784. env.keyword = keyword
  785. }
  786. func (env *accessibleReposEnv) SetSort(orderBy SearchOrderBy) {
  787. env.orderBy = orderBy
  788. }