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.

1036 lines
25 KiB

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