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.

1079 lines
26 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>
4 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>
4 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 years ago
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2016 The Gogs 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. "errors"
  8. "fmt"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "xorm.io/builder"
  14. "xorm.io/xorm"
  15. )
  16. const ownerTeamName = "Owners"
  17. // Team represents a organization team.
  18. type Team struct {
  19. ID int64 `xorm:"pk autoincr"`
  20. OrgID int64 `xorm:"INDEX"`
  21. LowerName string
  22. Name string
  23. Description string
  24. Authorize AccessMode
  25. Repos []*Repository `xorm:"-"`
  26. Members []*User `xorm:"-"`
  27. NumRepos int
  28. NumMembers int
  29. Units []*TeamUnit `xorm:"-"`
  30. IncludesAllRepositories bool `xorm:"NOT NULL DEFAULT false"`
  31. CanCreateOrgRepo bool `xorm:"NOT NULL DEFAULT false"`
  32. }
  33. // SearchTeamOptions holds the search options
  34. type SearchTeamOptions struct {
  35. ListOptions
  36. UserID int64
  37. Keyword string
  38. OrgID int64
  39. IncludeDesc bool
  40. }
  41. // SearchMembersOptions holds the search options
  42. type SearchMembersOptions struct {
  43. ListOptions
  44. }
  45. // SearchTeam search for teams. Caller is responsible to check permissions.
  46. func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) {
  47. if opts.Page <= 0 {
  48. opts.Page = 1
  49. }
  50. if opts.PageSize == 0 {
  51. // Default limit
  52. opts.PageSize = 10
  53. }
  54. var cond = builder.NewCond()
  55. if len(opts.Keyword) > 0 {
  56. lowerKeyword := strings.ToLower(opts.Keyword)
  57. var keywordCond builder.Cond = builder.Like{"lower_name", lowerKeyword}
  58. if opts.IncludeDesc {
  59. keywordCond = keywordCond.Or(builder.Like{"LOWER(description)", lowerKeyword})
  60. }
  61. cond = cond.And(keywordCond)
  62. }
  63. cond = cond.And(builder.Eq{"org_id": opts.OrgID})
  64. sess := x.NewSession()
  65. defer sess.Close()
  66. count, err := sess.
  67. Where(cond).
  68. Count(new(Team))
  69. if err != nil {
  70. return nil, 0, err
  71. }
  72. sess = sess.Where(cond)
  73. if opts.PageSize == -1 {
  74. opts.PageSize = int(count)
  75. } else {
  76. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  77. }
  78. teams := make([]*Team, 0, opts.PageSize)
  79. if err = sess.
  80. OrderBy("lower_name").
  81. Find(&teams); err != nil {
  82. return nil, 0, err
  83. }
  84. return teams, count, nil
  85. }
  86. // ColorFormat provides a basic color format for a Team
  87. func (t *Team) ColorFormat(s fmt.State) {
  88. log.ColorFprintf(s, "%d:%s (OrgID: %d) %-v",
  89. log.NewColoredIDValue(t.ID),
  90. t.Name,
  91. log.NewColoredIDValue(t.OrgID),
  92. t.Authorize)
  93. }
  94. // GetUnits return a list of available units for a team
  95. func (t *Team) GetUnits() error {
  96. return t.getUnits(x)
  97. }
  98. func (t *Team) getUnits(e Engine) (err error) {
  99. if t.Units != nil {
  100. return nil
  101. }
  102. t.Units, err = getUnitsByTeamID(e, t.ID)
  103. return err
  104. }
  105. // GetUnitNames returns the team units names
  106. func (t *Team) GetUnitNames() (res []string) {
  107. for _, u := range t.Units {
  108. res = append(res, Units[u.Type].NameKey)
  109. }
  110. return
  111. }
  112. // HasWriteAccess returns true if team has at least write level access mode.
  113. func (t *Team) HasWriteAccess() bool {
  114. return t.Authorize >= AccessModeWrite
  115. }
  116. // IsOwnerTeam returns true if team is owner team.
  117. func (t *Team) IsOwnerTeam() bool {
  118. return t.Name == ownerTeamName
  119. }
  120. // IsMember returns true if given user is a member of team.
  121. func (t *Team) IsMember(userID int64) bool {
  122. isMember, err := IsTeamMember(t.OrgID, t.ID, userID)
  123. if err != nil {
  124. log.Error("IsMember: %v", err)
  125. return false
  126. }
  127. return isMember
  128. }
  129. func (t *Team) getRepositories(e Engine) error {
  130. if t.Repos != nil {
  131. return nil
  132. }
  133. return e.Join("INNER", "team_repo", "repository.id = team_repo.repo_id").
  134. Where("team_repo.team_id=?", t.ID).
  135. OrderBy("repository.name").
  136. Find(&t.Repos)
  137. }
  138. // GetRepositories returns paginated repositories in team of organization.
  139. func (t *Team) GetRepositories(opts *SearchTeamOptions) error {
  140. if opts.Page == 0 {
  141. return t.getRepositories(x)
  142. }
  143. return t.getRepositories(opts.getPaginatedSession())
  144. }
  145. func (t *Team) getMembers(e Engine) (err error) {
  146. t.Members, err = getTeamMembers(e, t.ID)
  147. return err
  148. }
  149. // GetMembers returns paginated members in team of organization.
  150. func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) {
  151. if opts.Page == 0 {
  152. return t.getMembers(x)
  153. }
  154. return t.getMembers(opts.getPaginatedSession())
  155. }
  156. // AddMember adds new membership of the team to the organization,
  157. // the user will have membership to the organization automatically when needed.
  158. func (t *Team) AddMember(userID int64) error {
  159. return AddTeamMember(t, userID)
  160. }
  161. // RemoveMember removes member from team of organization.
  162. func (t *Team) RemoveMember(userID int64) error {
  163. return RemoveTeamMember(t, userID)
  164. }
  165. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  166. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  167. }
  168. // HasRepository returns true if given repository belong to team.
  169. func (t *Team) HasRepository(repoID int64) bool {
  170. return t.hasRepository(x, repoID)
  171. }
  172. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  173. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  174. return err
  175. }
  176. if _, err = e.Incr("num_repos").ID(t.ID).Update(new(Team)); err != nil {
  177. return fmt.Errorf("update team: %v", err)
  178. }
  179. t.NumRepos++
  180. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  181. return fmt.Errorf("recalculateAccesses: %v", err)
  182. }
  183. // Make all team members watch this repo if enabled in global settings
  184. if setting.Service.AutoWatchNewRepos {
  185. if err = t.getMembers(e); err != nil {
  186. return fmt.Errorf("getMembers: %v", err)
  187. }
  188. for _, u := range t.Members {
  189. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  190. return fmt.Errorf("watchRepo: %v", err)
  191. }
  192. }
  193. }
  194. return nil
  195. }
  196. // addAllRepositories adds all repositories to the team.
  197. // If the team already has some repositories they will be left unchanged.
  198. func (t *Team) addAllRepositories(e Engine) error {
  199. var orgRepos []Repository
  200. if err := e.Where("owner_id = ?", t.OrgID).Find(&orgRepos); err != nil {
  201. return fmt.Errorf("get org repos: %v", err)
  202. }
  203. for _, repo := range orgRepos {
  204. if !t.hasRepository(e, repo.ID) {
  205. if err := t.addRepository(e, &repo); err != nil {
  206. return fmt.Errorf("addRepository: %v", err)
  207. }
  208. }
  209. }
  210. return nil
  211. }
  212. // AddAllRepositories adds all repositories to the team
  213. func (t *Team) AddAllRepositories() (err error) {
  214. sess := x.NewSession()
  215. defer sess.Close()
  216. if err = sess.Begin(); err != nil {
  217. return err
  218. }
  219. if err = t.addAllRepositories(sess); err != nil {
  220. return err
  221. }
  222. return sess.Commit()
  223. }
  224. // AddRepository adds new repository to team of organization.
  225. func (t *Team) AddRepository(repo *Repository) (err error) {
  226. if repo.OwnerID != t.OrgID {
  227. return errors.New("Repository does not belong to organization")
  228. } else if t.HasRepository(repo.ID) {
  229. return nil
  230. }
  231. sess := x.NewSession()
  232. defer sess.Close()
  233. if err = sess.Begin(); err != nil {
  234. return err
  235. }
  236. if err = t.addRepository(sess, repo); err != nil {
  237. return err
  238. }
  239. return sess.Commit()
  240. }
  241. // RemoveAllRepositories removes all repositories from team and recalculates access
  242. func (t *Team) RemoveAllRepositories() (err error) {
  243. if t.IncludesAllRepositories {
  244. return nil
  245. }
  246. sess := x.NewSession()
  247. defer sess.Close()
  248. if err = sess.Begin(); err != nil {
  249. return err
  250. }
  251. if err = t.removeAllRepositories(sess); err != nil {
  252. return err
  253. }
  254. return sess.Commit()
  255. }
  256. // removeAllRepositories removes all repositories from team and recalculates access
  257. // Note: Shall not be called if team includes all repositories
  258. func (t *Team) removeAllRepositories(e Engine) (err error) {
  259. // Delete all accesses.
  260. for _, repo := range t.Repos {
  261. if err := repo.recalculateTeamAccesses(e, t.ID); err != nil {
  262. return err
  263. }
  264. // Remove watches from all users and now unaccessible repos
  265. for _, user := range t.Members {
  266. has, err := hasAccess(e, user.ID, repo)
  267. if err != nil {
  268. return err
  269. } else if has {
  270. continue
  271. }
  272. if err = watchRepo(e, user.ID, repo.ID, false); err != nil {
  273. return err
  274. }
  275. // Remove all IssueWatches a user has subscribed to in the repositories
  276. if err = removeIssueWatchersByRepoID(e, user.ID, repo.ID); err != nil {
  277. return err
  278. }
  279. }
  280. }
  281. // Delete team-repo
  282. if _, err := e.
  283. Where("team_id=?", t.ID).
  284. Delete(new(TeamRepo)); err != nil {
  285. return err
  286. }
  287. t.NumRepos = 0
  288. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. // removeRepository removes a repository from a team and recalculates access
  294. // Note: Repository shall not be removed from team if it includes all repositories (unless the repository is deleted)
  295. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  296. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  297. return err
  298. }
  299. t.NumRepos--
  300. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  301. return err
  302. }
  303. // Don't need to recalculate when delete a repository from organization.
  304. if recalculate {
  305. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  306. return err
  307. }
  308. }
  309. teamUsers, err := getTeamUsersByTeamID(e, t.ID)
  310. if err != nil {
  311. return fmt.Errorf("getTeamUsersByTeamID: %v", err)
  312. }
  313. for _, teamUser := range teamUsers {
  314. has, err := hasAccess(e, teamUser.UID, repo)
  315. if err != nil {
  316. return err
  317. } else if has {
  318. continue
  319. }
  320. if err = watchRepo(e, teamUser.UID, repo.ID, false); err != nil {
  321. return err
  322. }
  323. // Remove all IssueWatches a user has subscribed to in the repositories
  324. if err := removeIssueWatchersByRepoID(e, teamUser.UID, repo.ID); err != nil {
  325. return err
  326. }
  327. }
  328. return nil
  329. }
  330. // RemoveRepository removes repository from team of organization.
  331. // If the team shall include all repositories the request is ignored.
  332. func (t *Team) RemoveRepository(repoID int64) error {
  333. if !t.HasRepository(repoID) {
  334. return nil
  335. }
  336. if t.IncludesAllRepositories {
  337. return nil
  338. }
  339. repo, err := GetRepositoryByID(repoID)
  340. if err != nil {
  341. return err
  342. }
  343. sess := x.NewSession()
  344. defer sess.Close()
  345. if err = sess.Begin(); err != nil {
  346. return err
  347. }
  348. if err = t.removeRepository(sess, repo, true); err != nil {
  349. return err
  350. }
  351. return sess.Commit()
  352. }
  353. // UnitEnabled returns if the team has the given unit type enabled
  354. func (t *Team) UnitEnabled(tp UnitType) bool {
  355. return t.unitEnabled(x, tp)
  356. }
  357. func (t *Team) unitEnabled(e Engine, tp UnitType) bool {
  358. if err := t.getUnits(e); err != nil {
  359. log.Warn("Error loading team (ID: %d) units: %s", t.ID, err.Error())
  360. }
  361. for _, unit := range t.Units {
  362. if unit.Type == tp {
  363. return true
  364. }
  365. }
  366. return false
  367. }
  368. // IsUsableTeamName tests if a name could be as team name
  369. func IsUsableTeamName(name string) error {
  370. switch name {
  371. case "new":
  372. return ErrNameReserved{name}
  373. default:
  374. return nil
  375. }
  376. }
  377. // NewTeam creates a record of new team.
  378. // It's caller's responsibility to assign organization ID.
  379. func NewTeam(t *Team) (err error) {
  380. if len(t.Name) == 0 {
  381. return errors.New("empty team name")
  382. }
  383. if err = IsUsableTeamName(t.Name); err != nil {
  384. return err
  385. }
  386. has, err := x.ID(t.OrgID).Get(new(User))
  387. if err != nil {
  388. return err
  389. }
  390. if !has {
  391. return ErrOrgNotExist{t.OrgID, ""}
  392. }
  393. t.LowerName = strings.ToLower(t.Name)
  394. has, err = x.
  395. Where("org_id=?", t.OrgID).
  396. And("lower_name=?", t.LowerName).
  397. Get(new(Team))
  398. if err != nil {
  399. return err
  400. }
  401. if has {
  402. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  403. }
  404. sess := x.NewSession()
  405. defer sess.Close()
  406. if err = sess.Begin(); err != nil {
  407. return err
  408. }
  409. if _, err = sess.Insert(t); err != nil {
  410. errRollback := sess.Rollback()
  411. if errRollback != nil {
  412. log.Error("NewTeam sess.Rollback: %v", errRollback)
  413. }
  414. return err
  415. }
  416. // insert units for team
  417. if len(t.Units) > 0 {
  418. for _, unit := range t.Units {
  419. unit.TeamID = t.ID
  420. }
  421. if _, err = sess.Insert(&t.Units); err != nil {
  422. errRollback := sess.Rollback()
  423. if errRollback != nil {
  424. log.Error("NewTeam sess.Rollback: %v", errRollback)
  425. }
  426. return err
  427. }
  428. }
  429. // Add all repositories to the team if it has access to all of them.
  430. if t.IncludesAllRepositories {
  431. err = t.addAllRepositories(sess)
  432. if err != nil {
  433. return fmt.Errorf("addAllRepositories: %v", err)
  434. }
  435. }
  436. // Update organization number of teams.
  437. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  438. errRollback := sess.Rollback()
  439. if errRollback != nil {
  440. log.Error("NewTeam sess.Rollback: %v", errRollback)
  441. }
  442. return err
  443. }
  444. return sess.Commit()
  445. }
  446. func getTeam(e Engine, orgID int64, name string) (*Team, error) {
  447. t := &Team{
  448. OrgID: orgID,
  449. LowerName: strings.ToLower(name),
  450. }
  451. has, err := e.Get(t)
  452. if err != nil {
  453. return nil, err
  454. } else if !has {
  455. return nil, ErrTeamNotExist{orgID, 0, name}
  456. }
  457. return t, nil
  458. }
  459. // GetTeam returns team by given team name and organization.
  460. func GetTeam(orgID int64, name string) (*Team, error) {
  461. return getTeam(x, orgID, name)
  462. }
  463. // GetTeamIDsByNames returns a slice of team ids corresponds to names.
  464. func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) {
  465. ids := make([]int64, 0, len(names))
  466. for _, name := range names {
  467. u, err := GetTeam(orgID, name)
  468. if err != nil {
  469. if ignoreNonExistent {
  470. continue
  471. } else {
  472. return nil, err
  473. }
  474. }
  475. ids = append(ids, u.ID)
  476. }
  477. return ids, nil
  478. }
  479. // getOwnerTeam returns team by given team name and organization.
  480. func getOwnerTeam(e Engine, orgID int64) (*Team, error) {
  481. return getTeam(e, orgID, ownerTeamName)
  482. }
  483. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  484. t := new(Team)
  485. has, err := e.ID(teamID).Get(t)
  486. if err != nil {
  487. return nil, err
  488. } else if !has {
  489. return nil, ErrTeamNotExist{0, teamID, ""}
  490. }
  491. return t, nil
  492. }
  493. // GetTeamByID returns team by given ID.
  494. func GetTeamByID(teamID int64) (*Team, error) {
  495. return getTeamByID(x, teamID)
  496. }
  497. // GetTeamNamesByID returns team's lower name from a list of team ids.
  498. func GetTeamNamesByID(teamIDs []int64) ([]string, error) {
  499. if len(teamIDs) == 0 {
  500. return []string{}, nil
  501. }
  502. var teamNames []string
  503. err := x.Table("team").
  504. Select("lower_name").
  505. In("id", teamIDs).
  506. Asc("name").
  507. Find(&teamNames)
  508. return teamNames, err
  509. }
  510. // UpdateTeam updates information of team.
  511. func UpdateTeam(t *Team, authChanged bool, includeAllChanged bool) (err error) {
  512. if len(t.Name) == 0 {
  513. return errors.New("empty team name")
  514. }
  515. if len(t.Description) > 255 {
  516. t.Description = t.Description[:255]
  517. }
  518. sess := x.NewSession()
  519. defer sess.Close()
  520. if err = sess.Begin(); err != nil {
  521. return err
  522. }
  523. t.LowerName = strings.ToLower(t.Name)
  524. has, err := sess.
  525. Where("org_id=?", t.OrgID).
  526. And("lower_name=?", t.LowerName).
  527. And("id!=?", t.ID).
  528. Get(new(Team))
  529. if err != nil {
  530. return err
  531. } else if has {
  532. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  533. }
  534. if _, err = sess.ID(t.ID).Cols("name", "lower_name", "description",
  535. "can_create_org_repo", "authorize", "includes_all_repositories").Update(t); err != nil {
  536. return fmt.Errorf("update: %v", err)
  537. }
  538. // update units for team
  539. if len(t.Units) > 0 {
  540. for _, unit := range t.Units {
  541. unit.TeamID = t.ID
  542. }
  543. // Delete team-unit.
  544. if _, err := sess.
  545. Where("team_id=?", t.ID).
  546. Delete(new(TeamUnit)); err != nil {
  547. return err
  548. }
  549. if _, err = sess.Cols("org_id", "team_id", "type").Insert(&t.Units); err != nil {
  550. errRollback := sess.Rollback()
  551. if errRollback != nil {
  552. log.Error("UpdateTeam sess.Rollback: %v", errRollback)
  553. }
  554. return err
  555. }
  556. }
  557. // Update access for team members if needed.
  558. if authChanged {
  559. if err = t.getRepositories(sess); err != nil {
  560. return fmt.Errorf("getRepositories: %v", err)
  561. }
  562. for _, repo := range t.Repos {
  563. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  564. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  565. }
  566. }
  567. }
  568. // Add all repositories to the team if it has access to all of them.
  569. if includeAllChanged && t.IncludesAllRepositories {
  570. err = t.addAllRepositories(sess)
  571. if err != nil {
  572. return fmt.Errorf("addAllRepositories: %v", err)
  573. }
  574. }
  575. return sess.Commit()
  576. }
  577. // DeleteTeam deletes given team.
  578. // It's caller's responsibility to assign organization ID.
  579. func DeleteTeam(t *Team) error {
  580. if err := t.GetRepositories(&SearchTeamOptions{}); err != nil {
  581. return err
  582. }
  583. sess := x.NewSession()
  584. defer sess.Close()
  585. if err := sess.Begin(); err != nil {
  586. return err
  587. }
  588. if err := t.getMembers(sess); err != nil {
  589. return err
  590. }
  591. if err := t.removeAllRepositories(sess); err != nil {
  592. return err
  593. }
  594. // Delete team-user.
  595. if _, err := sess.
  596. Where("org_id=?", t.OrgID).
  597. Where("team_id=?", t.ID).
  598. Delete(new(TeamUser)); err != nil {
  599. return err
  600. }
  601. // Delete team-unit.
  602. if _, err := sess.
  603. Where("team_id=?", t.ID).
  604. Delete(new(TeamUnit)); err != nil {
  605. return err
  606. }
  607. // Delete team.
  608. if _, err := sess.ID(t.ID).Delete(new(Team)); err != nil {
  609. return err
  610. }
  611. // Update organization number of teams.
  612. if _, err := sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  613. return err
  614. }
  615. return sess.Commit()
  616. }
  617. // ___________ ____ ___
  618. // \__ ___/___ _____ _____ | | \______ ___________
  619. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  620. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  621. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  622. // \/ \/ \/ \/ \/
  623. // TeamUser represents an team-user relation.
  624. type TeamUser struct {
  625. ID int64 `xorm:"pk autoincr"`
  626. OrgID int64 `xorm:"INDEX"`
  627. TeamID int64 `xorm:"UNIQUE(s)"`
  628. UID int64 `xorm:"UNIQUE(s)"`
  629. }
  630. func isTeamMember(e Engine, orgID, teamID, userID int64) (bool, error) {
  631. return e.
  632. Where("org_id=?", orgID).
  633. And("team_id=?", teamID).
  634. And("uid=?", userID).
  635. Table("team_user").
  636. Exist()
  637. }
  638. // IsTeamMember returns true if given user is a member of team.
  639. func IsTeamMember(orgID, teamID, userID int64) (bool, error) {
  640. return isTeamMember(x, orgID, teamID, userID)
  641. }
  642. func getTeamUsersByTeamID(e Engine, teamID int64) ([]*TeamUser, error) {
  643. teamUsers := make([]*TeamUser, 0, 10)
  644. return teamUsers, e.
  645. Where("team_id=?", teamID).
  646. Find(&teamUsers)
  647. }
  648. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  649. teamUsers, err := getTeamUsersByTeamID(e, teamID)
  650. if err != nil {
  651. return nil, fmt.Errorf("get team-users: %v", err)
  652. }
  653. members := make([]*User, len(teamUsers))
  654. for i, teamUser := range teamUsers {
  655. member, err := getUserByID(e, teamUser.UID)
  656. if err != nil {
  657. return nil, fmt.Errorf("get user '%d': %v", teamUser.UID, err)
  658. }
  659. members[i] = member
  660. }
  661. sort.Slice(members, func(i, j int) bool {
  662. return members[i].DisplayName() < members[j].DisplayName()
  663. })
  664. return members, nil
  665. }
  666. // GetTeamMembers returns all members in given team of organization.
  667. func GetTeamMembers(teamID int64) ([]*User, error) {
  668. return getTeamMembers(x, teamID)
  669. }
  670. func getUserTeams(e Engine, userID int64, listOptions ListOptions) (teams []*Team, err error) {
  671. sess := e.
  672. Join("INNER", "team_user", "team_user.team_id = team.id").
  673. Where("team_user.uid=?", userID)
  674. if listOptions.Page != 0 {
  675. sess = listOptions.setSessionPagination(sess)
  676. }
  677. return teams, sess.Find(&teams)
  678. }
  679. func getUserOrgTeams(e Engine, orgID, userID int64) (teams []*Team, err error) {
  680. return teams, e.
  681. Join("INNER", "team_user", "team_user.team_id = team.id").
  682. Where("team.org_id = ?", orgID).
  683. And("team_user.uid=?", userID).
  684. Find(&teams)
  685. }
  686. func getUserRepoTeams(e Engine, orgID, userID, repoID int64) (teams []*Team, err error) {
  687. return teams, e.
  688. Join("INNER", "team_user", "team_user.team_id = team.id").
  689. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  690. Where("team.org_id = ?", orgID).
  691. And("team_user.uid=?", userID).
  692. And("team_repo.repo_id=?", repoID).
  693. Find(&teams)
  694. }
  695. // GetUserOrgTeams returns all teams that user belongs to in given organization.
  696. func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) {
  697. return getUserOrgTeams(x, orgID, userID)
  698. }
  699. // GetUserTeams returns all teams that user belongs across all organizations.
  700. func GetUserTeams(userID int64, listOptions ListOptions) ([]*Team, error) {
  701. return getUserTeams(x, userID, listOptions)
  702. }
  703. // AddTeamMember adds new membership of given team to given organization,
  704. // the user will have membership to given organization automatically when needed.
  705. func AddTeamMember(team *Team, userID int64) error {
  706. isAlreadyMember, err := IsTeamMember(team.OrgID, team.ID, userID)
  707. if err != nil || isAlreadyMember {
  708. return err
  709. }
  710. if err := AddOrgUser(team.OrgID, userID); err != nil {
  711. return err
  712. }
  713. // Get team and its repositories.
  714. if err := team.GetRepositories(&SearchTeamOptions{}); err != nil {
  715. return err
  716. }
  717. sess := x.NewSession()
  718. defer sess.Close()
  719. if err := sess.Begin(); err != nil {
  720. return err
  721. }
  722. if _, err := sess.Insert(&TeamUser{
  723. UID: userID,
  724. OrgID: team.OrgID,
  725. TeamID: team.ID,
  726. }); err != nil {
  727. return err
  728. } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(Team)); err != nil {
  729. return err
  730. }
  731. team.NumMembers++
  732. // Give access to team repositories.
  733. for _, repo := range team.Repos {
  734. if err := repo.recalculateUserAccess(sess, userID); err != nil {
  735. return err
  736. }
  737. if setting.Service.AutoWatchNewRepos {
  738. if err = watchRepo(sess, userID, repo.ID, true); err != nil {
  739. return err
  740. }
  741. }
  742. }
  743. return sess.Commit()
  744. }
  745. func removeTeamMember(e *xorm.Session, team *Team, userID int64) error {
  746. isMember, err := isTeamMember(e, team.OrgID, team.ID, userID)
  747. if err != nil || !isMember {
  748. return err
  749. }
  750. // Check if the user to delete is the last member in owner team.
  751. if team.IsOwnerTeam() && team.NumMembers == 1 {
  752. return ErrLastOrgOwner{UID: userID}
  753. }
  754. team.NumMembers--
  755. if err := team.getRepositories(e); err != nil {
  756. return err
  757. }
  758. if _, err := e.Delete(&TeamUser{
  759. UID: userID,
  760. OrgID: team.OrgID,
  761. TeamID: team.ID,
  762. }); err != nil {
  763. return err
  764. } else if _, err = e.
  765. ID(team.ID).
  766. Cols("num_members").
  767. Update(team); err != nil {
  768. return err
  769. }
  770. // Delete access to team repositories.
  771. for _, repo := range team.Repos {
  772. if err := repo.recalculateUserAccess(e, userID); err != nil {
  773. return err
  774. }
  775. // Remove watches from now unaccessible
  776. if err := repo.reconsiderWatches(e, userID); err != nil {
  777. return err
  778. }
  779. // Remove issue assignments from now unaccessible
  780. if err := repo.reconsiderIssueAssignees(e, userID); err != nil {
  781. return err
  782. }
  783. }
  784. // Check if the user is a member of any team in the organization.
  785. if count, err := e.Count(&TeamUser{
  786. UID: userID,
  787. OrgID: team.OrgID,
  788. }); err != nil {
  789. return err
  790. } else if count == 0 {
  791. return removeOrgUser(e, team.OrgID, userID)
  792. }
  793. return nil
  794. }
  795. // RemoveTeamMember removes member from given team of given organization.
  796. func RemoveTeamMember(team *Team, userID int64) error {
  797. sess := x.NewSession()
  798. defer sess.Close()
  799. if err := sess.Begin(); err != nil {
  800. return err
  801. }
  802. if err := removeTeamMember(sess, team, userID); err != nil {
  803. return err
  804. }
  805. return sess.Commit()
  806. }
  807. // IsUserInTeams returns if a user in some teams
  808. func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) {
  809. return isUserInTeams(x, userID, teamIDs)
  810. }
  811. func isUserInTeams(e Engine, userID int64, teamIDs []int64) (bool, error) {
  812. return e.Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser))
  813. }
  814. // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
  815. func UsersInTeamsCount(userIDs []int64, teamIDs []int64) (int64, error) {
  816. var ids []int64
  817. if err := x.In("uid", userIDs).In("team_id", teamIDs).
  818. Table("team_user").
  819. Cols("uid").GroupBy("uid").Find(&ids); err != nil {
  820. return 0, err
  821. }
  822. return int64(len(ids)), nil
  823. }
  824. // ___________ __________
  825. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  826. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  827. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  828. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  829. // \/ \/ \/ \/ \/|__|
  830. // TeamRepo represents an team-repository relation.
  831. type TeamRepo struct {
  832. ID int64 `xorm:"pk autoincr"`
  833. OrgID int64 `xorm:"INDEX"`
  834. TeamID int64 `xorm:"UNIQUE(s)"`
  835. RepoID int64 `xorm:"UNIQUE(s)"`
  836. }
  837. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  838. has, _ := e.
  839. Where("org_id=?", orgID).
  840. And("team_id=?", teamID).
  841. And("repo_id=?", repoID).
  842. Get(new(TeamRepo))
  843. return has
  844. }
  845. // HasTeamRepo returns true if given repository belongs to team.
  846. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  847. return hasTeamRepo(x, orgID, teamID, repoID)
  848. }
  849. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  850. _, err := e.InsertOne(&TeamRepo{
  851. OrgID: orgID,
  852. TeamID: teamID,
  853. RepoID: repoID,
  854. })
  855. return err
  856. }
  857. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  858. _, err := e.Delete(&TeamRepo{
  859. TeamID: teamID,
  860. RepoID: repoID,
  861. })
  862. return err
  863. }
  864. // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
  865. func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
  866. teams := make([]*Team, 0, 5)
  867. return teams, x.Where("team.authorize >= ?", mode).
  868. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  869. And("team_repo.org_id = ?", orgID).
  870. And("team_repo.repo_id = ?", repoID).
  871. Find(&teams)
  872. }
  873. // ___________ ____ ___ .__ __
  874. // \__ ___/___ _____ _____ | | \____ |__|/ |_
  875. // | |_/ __ \\__ \ / \| | / \| \ __\
  876. // | |\ ___/ / __ \| Y Y \ | / | \ || |
  877. // |____| \___ >____ /__|_| /______/|___| /__||__|
  878. // \/ \/ \/ \/
  879. // TeamUnit describes all units of a repository
  880. type TeamUnit struct {
  881. ID int64 `xorm:"pk autoincr"`
  882. OrgID int64 `xorm:"INDEX"`
  883. TeamID int64 `xorm:"UNIQUE(s)"`
  884. Type UnitType `xorm:"UNIQUE(s)"`
  885. }
  886. // Unit returns Unit
  887. func (t *TeamUnit) Unit() Unit {
  888. return Units[t.Type]
  889. }
  890. func getUnitsByTeamID(e Engine, teamID int64) (units []*TeamUnit, err error) {
  891. return units, e.Where("team_id = ?", teamID).Find(&units)
  892. }
  893. // UpdateTeamUnits updates a teams's units
  894. func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) {
  895. sess := x.NewSession()
  896. defer sess.Close()
  897. if err = sess.Begin(); err != nil {
  898. return err
  899. }
  900. if _, err = sess.Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil {
  901. return err
  902. }
  903. if len(units) > 0 {
  904. if _, err = sess.Insert(units); err != nil {
  905. errRollback := sess.Rollback()
  906. if errRollback != nil {
  907. log.Error("UpdateTeamUnits sess.Rollback: %v", errRollback)
  908. }
  909. return err
  910. }
  911. }
  912. return sess.Commit()
  913. }