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.

839 lines
20 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. "github.com/go-xorm/xorm"
  14. )
  15. const ownerTeamName = "Owners"
  16. // Team represents a organization team.
  17. type Team struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. OrgID int64 `xorm:"INDEX"`
  20. LowerName string
  21. Name string
  22. Description string
  23. Authorize AccessMode
  24. Repos []*Repository `xorm:"-"`
  25. Members []*User `xorm:"-"`
  26. NumRepos int
  27. NumMembers int
  28. Units []*TeamUnit `xorm:"-"`
  29. }
  30. // GetUnits return a list of available units for a team
  31. func (t *Team) GetUnits() error {
  32. return t.getUnits(x)
  33. }
  34. func (t *Team) getUnits(e Engine) (err error) {
  35. if t.Units != nil {
  36. return nil
  37. }
  38. t.Units, err = getUnitsByTeamID(e, t.ID)
  39. return err
  40. }
  41. // GetUnitNames returns the team units names
  42. func (t *Team) GetUnitNames() (res []string) {
  43. for _, u := range t.Units {
  44. res = append(res, Units[u.Type].NameKey)
  45. }
  46. return
  47. }
  48. // HasWriteAccess returns true if team has at least write level access mode.
  49. func (t *Team) HasWriteAccess() bool {
  50. return t.Authorize >= AccessModeWrite
  51. }
  52. // IsOwnerTeam returns true if team is owner team.
  53. func (t *Team) IsOwnerTeam() bool {
  54. return t.Name == ownerTeamName
  55. }
  56. // IsMember returns true if given user is a member of team.
  57. func (t *Team) IsMember(userID int64) bool {
  58. isMember, err := IsTeamMember(t.OrgID, t.ID, userID)
  59. if err != nil {
  60. log.Error("IsMember: %v", err)
  61. return false
  62. }
  63. return isMember
  64. }
  65. func (t *Team) getRepositories(e Engine) error {
  66. return e.Join("INNER", "team_repo", "repository.id = team_repo.repo_id").
  67. Where("team_repo.team_id=?", t.ID).
  68. OrderBy("repository.name").
  69. Find(&t.Repos)
  70. }
  71. // GetRepositories returns all repositories in team of organization.
  72. func (t *Team) GetRepositories() error {
  73. return t.getRepositories(x)
  74. }
  75. func (t *Team) getMembers(e Engine) (err error) {
  76. t.Members, err = getTeamMembers(e, t.ID)
  77. return err
  78. }
  79. // GetMembers returns all members in team of organization.
  80. func (t *Team) GetMembers() (err error) {
  81. return t.getMembers(x)
  82. }
  83. // AddMember adds new membership of the team to the organization,
  84. // the user will have membership to the organization automatically when needed.
  85. func (t *Team) AddMember(userID int64) error {
  86. return AddTeamMember(t, userID)
  87. }
  88. // RemoveMember removes member from team of organization.
  89. func (t *Team) RemoveMember(userID int64) error {
  90. return RemoveTeamMember(t, userID)
  91. }
  92. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  93. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  94. }
  95. // HasRepository returns true if given repository belong to team.
  96. func (t *Team) HasRepository(repoID int64) bool {
  97. return t.hasRepository(x, repoID)
  98. }
  99. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  100. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  101. return err
  102. }
  103. if _, err = e.Incr("num_repos").ID(t.ID).Update(new(Team)); err != nil {
  104. return fmt.Errorf("update team: %v", err)
  105. }
  106. t.NumRepos++
  107. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  108. return fmt.Errorf("recalculateAccesses: %v", err)
  109. }
  110. // Make all team members watch this repo if enabled in global settings
  111. if setting.Service.AutoWatchNewRepos {
  112. if err = t.getMembers(e); err != nil {
  113. return fmt.Errorf("getMembers: %v", err)
  114. }
  115. for _, u := range t.Members {
  116. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  117. return fmt.Errorf("watchRepo: %v", err)
  118. }
  119. }
  120. }
  121. return nil
  122. }
  123. // AddRepository adds new repository to team of organization.
  124. func (t *Team) AddRepository(repo *Repository) (err error) {
  125. if repo.OwnerID != t.OrgID {
  126. return errors.New("Repository does not belong to organization")
  127. } else if t.HasRepository(repo.ID) {
  128. return nil
  129. }
  130. sess := x.NewSession()
  131. defer sess.Close()
  132. if err = sess.Begin(); err != nil {
  133. return err
  134. }
  135. if err = t.addRepository(sess, repo); err != nil {
  136. return err
  137. }
  138. return sess.Commit()
  139. }
  140. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  141. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  142. return err
  143. }
  144. t.NumRepos--
  145. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  146. return err
  147. }
  148. // Don't need to recalculate when delete a repository from organization.
  149. if recalculate {
  150. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  151. return err
  152. }
  153. }
  154. teamUsers, err := getTeamUsersByTeamID(e, t.ID)
  155. if err != nil {
  156. return fmt.Errorf("getTeamUsersByTeamID: %v", err)
  157. }
  158. for _, teamUser := range teamUsers {
  159. has, err := hasAccess(e, teamUser.UID, repo)
  160. if err != nil {
  161. return err
  162. } else if has {
  163. continue
  164. }
  165. if err = watchRepo(e, teamUser.UID, repo.ID, false); err != nil {
  166. return err
  167. }
  168. // Remove all IssueWatches a user has subscribed to in the repositories
  169. if err := removeIssueWatchersByRepoID(e, teamUser.UID, repo.ID); err != nil {
  170. return err
  171. }
  172. }
  173. return nil
  174. }
  175. // RemoveRepository removes repository from team of organization.
  176. func (t *Team) RemoveRepository(repoID int64) error {
  177. if !t.HasRepository(repoID) {
  178. return nil
  179. }
  180. repo, err := GetRepositoryByID(repoID)
  181. if err != nil {
  182. return err
  183. }
  184. sess := x.NewSession()
  185. defer sess.Close()
  186. if err = sess.Begin(); err != nil {
  187. return err
  188. }
  189. if err = t.removeRepository(sess, repo, true); err != nil {
  190. return err
  191. }
  192. return sess.Commit()
  193. }
  194. // UnitEnabled returns if the team has the given unit type enabled
  195. func (t *Team) UnitEnabled(tp UnitType) bool {
  196. return t.unitEnabled(x, tp)
  197. }
  198. func (t *Team) unitEnabled(e Engine, tp UnitType) bool {
  199. if err := t.getUnits(e); err != nil {
  200. log.Warn("Error loading repository (ID: %d) units: %s", t.ID, err.Error())
  201. }
  202. for _, unit := range t.Units {
  203. if unit.Type == tp {
  204. return true
  205. }
  206. }
  207. return false
  208. }
  209. // IsUsableTeamName tests if a name could be as team name
  210. func IsUsableTeamName(name string) error {
  211. switch name {
  212. case "new":
  213. return ErrNameReserved{name}
  214. default:
  215. return nil
  216. }
  217. }
  218. // NewTeam creates a record of new team.
  219. // It's caller's responsibility to assign organization ID.
  220. func NewTeam(t *Team) (err error) {
  221. if len(t.Name) == 0 {
  222. return errors.New("empty team name")
  223. }
  224. if err = IsUsableTeamName(t.Name); err != nil {
  225. return err
  226. }
  227. has, err := x.ID(t.OrgID).Get(new(User))
  228. if err != nil {
  229. return err
  230. } else if !has {
  231. return ErrOrgNotExist{t.OrgID, ""}
  232. }
  233. t.LowerName = strings.ToLower(t.Name)
  234. has, err = x.
  235. Where("org_id=?", t.OrgID).
  236. And("lower_name=?", t.LowerName).
  237. Get(new(Team))
  238. if err != nil {
  239. return err
  240. } else if has {
  241. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  242. }
  243. sess := x.NewSession()
  244. defer sess.Close()
  245. if err = sess.Begin(); err != nil {
  246. return err
  247. }
  248. if _, err = sess.Insert(t); err != nil {
  249. sess.Rollback()
  250. return err
  251. }
  252. // insert units for team
  253. if len(t.Units) > 0 {
  254. for _, unit := range t.Units {
  255. unit.TeamID = t.ID
  256. }
  257. if _, err = sess.Insert(&t.Units); err != nil {
  258. sess.Rollback()
  259. return err
  260. }
  261. }
  262. // Update organization number of teams.
  263. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  264. sess.Rollback()
  265. return err
  266. }
  267. return sess.Commit()
  268. }
  269. func getTeam(e Engine, orgID int64, name string) (*Team, error) {
  270. t := &Team{
  271. OrgID: orgID,
  272. LowerName: strings.ToLower(name),
  273. }
  274. has, err := e.Get(t)
  275. if err != nil {
  276. return nil, err
  277. } else if !has {
  278. return nil, ErrTeamNotExist
  279. }
  280. return t, nil
  281. }
  282. // GetTeam returns team by given team name and organization.
  283. func GetTeam(orgID int64, name string) (*Team, error) {
  284. return getTeam(x, orgID, name)
  285. }
  286. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  287. t := new(Team)
  288. has, err := e.ID(teamID).Get(t)
  289. if err != nil {
  290. return nil, err
  291. } else if !has {
  292. return nil, ErrTeamNotExist
  293. }
  294. return t, nil
  295. }
  296. // GetTeamByID returns team by given ID.
  297. func GetTeamByID(teamID int64) (*Team, error) {
  298. return getTeamByID(x, teamID)
  299. }
  300. // UpdateTeam updates information of team.
  301. func UpdateTeam(t *Team, authChanged bool) (err error) {
  302. if len(t.Name) == 0 {
  303. return errors.New("empty team name")
  304. }
  305. if len(t.Description) > 255 {
  306. t.Description = t.Description[:255]
  307. }
  308. sess := x.NewSession()
  309. defer sess.Close()
  310. if err = sess.Begin(); err != nil {
  311. return err
  312. }
  313. t.LowerName = strings.ToLower(t.Name)
  314. has, err := sess.
  315. Where("org_id=?", t.OrgID).
  316. And("lower_name=?", t.LowerName).
  317. And("id!=?", t.ID).
  318. Get(new(Team))
  319. if err != nil {
  320. return err
  321. } else if has {
  322. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  323. }
  324. if _, err = sess.ID(t.ID).AllCols().Update(t); err != nil {
  325. return fmt.Errorf("update: %v", err)
  326. }
  327. // update units for team
  328. if len(t.Units) > 0 {
  329. for _, unit := range t.Units {
  330. unit.TeamID = t.ID
  331. }
  332. // Delete team-unit.
  333. if _, err := sess.
  334. Where("team_id=?", t.ID).
  335. Delete(new(TeamUnit)); err != nil {
  336. return err
  337. }
  338. if _, err = sess.Insert(&t.Units); err != nil {
  339. sess.Rollback()
  340. return err
  341. }
  342. }
  343. // Update access for team members if needed.
  344. if authChanged {
  345. if err = t.getRepositories(sess); err != nil {
  346. return fmt.Errorf("getRepositories: %v", err)
  347. }
  348. for _, repo := range t.Repos {
  349. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  350. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  351. }
  352. }
  353. }
  354. return sess.Commit()
  355. }
  356. // DeleteTeam deletes given team.
  357. // It's caller's responsibility to assign organization ID.
  358. func DeleteTeam(t *Team) error {
  359. if err := t.GetRepositories(); err != nil {
  360. return err
  361. }
  362. sess := x.NewSession()
  363. defer sess.Close()
  364. if err := sess.Begin(); err != nil {
  365. return err
  366. }
  367. if err := t.getMembers(sess); err != nil {
  368. return err
  369. }
  370. // Delete all accesses.
  371. for _, repo := range t.Repos {
  372. if err := repo.recalculateTeamAccesses(sess, t.ID); err != nil {
  373. return err
  374. }
  375. // Remove watches from all users and now unaccessible repos
  376. for _, user := range t.Members {
  377. has, err := hasAccess(sess, user.ID, repo)
  378. if err != nil {
  379. return err
  380. } else if has {
  381. continue
  382. }
  383. if err = watchRepo(sess, user.ID, repo.ID, false); err != nil {
  384. return err
  385. }
  386. // Remove all IssueWatches a user has subscribed to in the repositories
  387. if err = removeIssueWatchersByRepoID(sess, user.ID, repo.ID); err != nil {
  388. return err
  389. }
  390. }
  391. }
  392. // Delete team-repo
  393. if _, err := sess.
  394. Where("team_id=?", t.ID).
  395. Delete(new(TeamRepo)); err != nil {
  396. return err
  397. }
  398. // Delete team-user.
  399. if _, err := sess.
  400. Where("org_id=?", t.OrgID).
  401. Where("team_id=?", t.ID).
  402. Delete(new(TeamUser)); err != nil {
  403. return err
  404. }
  405. // Delete team-unit.
  406. if _, err := sess.
  407. Where("team_id=?", t.ID).
  408. Delete(new(TeamUnit)); err != nil {
  409. return err
  410. }
  411. // Delete team.
  412. if _, err := sess.ID(t.ID).Delete(new(Team)); err != nil {
  413. return err
  414. }
  415. // Update organization number of teams.
  416. if _, err := sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  417. return err
  418. }
  419. return sess.Commit()
  420. }
  421. // ___________ ____ ___
  422. // \__ ___/___ _____ _____ | | \______ ___________
  423. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  424. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  425. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  426. // \/ \/ \/ \/ \/
  427. // TeamUser represents an team-user relation.
  428. type TeamUser struct {
  429. ID int64 `xorm:"pk autoincr"`
  430. OrgID int64 `xorm:"INDEX"`
  431. TeamID int64 `xorm:"UNIQUE(s)"`
  432. UID int64 `xorm:"UNIQUE(s)"`
  433. }
  434. func isTeamMember(e Engine, orgID, teamID, userID int64) (bool, error) {
  435. return e.
  436. Where("org_id=?", orgID).
  437. And("team_id=?", teamID).
  438. And("uid=?", userID).
  439. Table("team_user").
  440. Exist()
  441. }
  442. // IsTeamMember returns true if given user is a member of team.
  443. func IsTeamMember(orgID, teamID, userID int64) (bool, error) {
  444. return isTeamMember(x, orgID, teamID, userID)
  445. }
  446. func getTeamUsersByTeamID(e Engine, teamID int64) ([]*TeamUser, error) {
  447. teamUsers := make([]*TeamUser, 0, 10)
  448. return teamUsers, e.
  449. Where("team_id=?", teamID).
  450. Find(&teamUsers)
  451. }
  452. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  453. teamUsers, err := getTeamUsersByTeamID(e, teamID)
  454. if err != nil {
  455. return nil, fmt.Errorf("get team-users: %v", err)
  456. }
  457. members := make([]*User, len(teamUsers))
  458. for i, teamUser := range teamUsers {
  459. member, err := getUserByID(e, teamUser.UID)
  460. if err != nil {
  461. return nil, fmt.Errorf("get user '%d': %v", teamUser.UID, err)
  462. }
  463. members[i] = member
  464. }
  465. sort.Slice(members, func(i, j int) bool {
  466. return members[i].DisplayName() < members[j].DisplayName()
  467. })
  468. return members, nil
  469. }
  470. // GetTeamMembers returns all members in given team of organization.
  471. func GetTeamMembers(teamID int64) ([]*User, error) {
  472. return getTeamMembers(x, teamID)
  473. }
  474. func getUserTeams(e Engine, userID int64) (teams []*Team, err error) {
  475. return teams, e.
  476. Join("INNER", "team_user", "team_user.team_id = team.id").
  477. Where("team_user.uid=?", userID).
  478. Find(&teams)
  479. }
  480. func getUserOrgTeams(e Engine, orgID, userID int64) (teams []*Team, err error) {
  481. return teams, e.
  482. Join("INNER", "team_user", "team_user.team_id = team.id").
  483. Where("team.org_id = ?", orgID).
  484. And("team_user.uid=?", userID).
  485. Find(&teams)
  486. }
  487. func getUserRepoTeams(e Engine, orgID, userID, repoID int64) (teams []*Team, err error) {
  488. return teams, e.
  489. Join("INNER", "team_user", "team_user.team_id = team.id").
  490. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  491. Where("team.org_id = ?", orgID).
  492. And("team_user.uid=?", userID).
  493. And("team_repo.repo_id=?", repoID).
  494. Find(&teams)
  495. }
  496. // GetUserOrgTeams returns all teams that user belongs to in given organization.
  497. func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) {
  498. return getUserOrgTeams(x, orgID, userID)
  499. }
  500. // GetUserTeams returns all teams that user belongs across all organizations.
  501. func GetUserTeams(userID int64) ([]*Team, error) {
  502. return getUserTeams(x, userID)
  503. }
  504. // AddTeamMember adds new membership of given team to given organization,
  505. // the user will have membership to given organization automatically when needed.
  506. func AddTeamMember(team *Team, userID int64) error {
  507. isAlreadyMember, err := IsTeamMember(team.OrgID, team.ID, userID)
  508. if err != nil || isAlreadyMember {
  509. return err
  510. }
  511. if err := AddOrgUser(team.OrgID, userID); err != nil {
  512. return err
  513. }
  514. // Get team and its repositories.
  515. if err := team.GetRepositories(); err != nil {
  516. return err
  517. }
  518. sess := x.NewSession()
  519. defer sess.Close()
  520. if err := sess.Begin(); err != nil {
  521. return err
  522. }
  523. if _, err := sess.Insert(&TeamUser{
  524. UID: userID,
  525. OrgID: team.OrgID,
  526. TeamID: team.ID,
  527. }); err != nil {
  528. return err
  529. } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(Team)); err != nil {
  530. return err
  531. }
  532. team.NumMembers++
  533. // Give access to team repositories.
  534. for _, repo := range team.Repos {
  535. if err := repo.recalculateTeamAccesses(sess, 0); err != nil {
  536. return err
  537. }
  538. if setting.Service.AutoWatchNewRepos {
  539. if err = watchRepo(sess, userID, repo.ID, true); err != nil {
  540. return err
  541. }
  542. }
  543. }
  544. return sess.Commit()
  545. }
  546. func removeTeamMember(e *xorm.Session, team *Team, userID int64) error {
  547. isMember, err := isTeamMember(e, team.OrgID, team.ID, userID)
  548. if err != nil || !isMember {
  549. return err
  550. }
  551. // Check if the user to delete is the last member in owner team.
  552. if team.IsOwnerTeam() && team.NumMembers == 1 {
  553. return ErrLastOrgOwner{UID: userID}
  554. }
  555. team.NumMembers--
  556. if err := team.getRepositories(e); err != nil {
  557. return err
  558. }
  559. if _, err := e.Delete(&TeamUser{
  560. UID: userID,
  561. OrgID: team.OrgID,
  562. TeamID: team.ID,
  563. }); err != nil {
  564. return err
  565. } else if _, err = e.
  566. ID(team.ID).
  567. Cols("num_members").
  568. Update(team); err != nil {
  569. return err
  570. }
  571. // Delete access to team repositories.
  572. for _, repo := range team.Repos {
  573. if err := repo.recalculateTeamAccesses(e, 0); err != nil {
  574. return err
  575. }
  576. // Remove watches from now unaccessible
  577. has, err := hasAccess(e, userID, repo)
  578. if err != nil {
  579. return err
  580. } else if has {
  581. continue
  582. }
  583. if err = watchRepo(e, userID, repo.ID, false); err != nil {
  584. return err
  585. }
  586. // Remove all IssueWatches a user has subscribed to in the repositories
  587. if err := removeIssueWatchersByRepoID(e, userID, repo.ID); err != nil {
  588. return err
  589. }
  590. }
  591. // Check if the user is a member of any team in the organization.
  592. if count, err := e.Count(&TeamUser{
  593. UID: userID,
  594. OrgID: team.OrgID,
  595. }); err != nil {
  596. return err
  597. } else if count == 0 {
  598. return removeOrgUser(e, team.OrgID, userID)
  599. }
  600. return nil
  601. }
  602. // RemoveTeamMember removes member from given team of given organization.
  603. func RemoveTeamMember(team *Team, userID int64) error {
  604. sess := x.NewSession()
  605. defer sess.Close()
  606. if err := sess.Begin(); err != nil {
  607. return err
  608. }
  609. if err := removeTeamMember(sess, team, userID); err != nil {
  610. return err
  611. }
  612. return sess.Commit()
  613. }
  614. // IsUserInTeams returns if a user in some teams
  615. func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) {
  616. return x.Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser))
  617. }
  618. // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
  619. func UsersInTeamsCount(userIDs []int64, teamIDs []int64) (count int64, err error) {
  620. if count, err = x.In("uid", userIDs).In("team_id", teamIDs).Count(new(TeamUser)); err != nil {
  621. return 0, err
  622. }
  623. return
  624. }
  625. // ___________ __________
  626. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  627. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  628. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  629. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  630. // \/ \/ \/ \/ \/|__|
  631. // TeamRepo represents an team-repository relation.
  632. type TeamRepo struct {
  633. ID int64 `xorm:"pk autoincr"`
  634. OrgID int64 `xorm:"INDEX"`
  635. TeamID int64 `xorm:"UNIQUE(s)"`
  636. RepoID int64 `xorm:"UNIQUE(s)"`
  637. }
  638. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  639. has, _ := e.
  640. Where("org_id=?", orgID).
  641. And("team_id=?", teamID).
  642. And("repo_id=?", repoID).
  643. Get(new(TeamRepo))
  644. return has
  645. }
  646. // HasTeamRepo returns true if given repository belongs to team.
  647. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  648. return hasTeamRepo(x, orgID, teamID, repoID)
  649. }
  650. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  651. _, err := e.InsertOne(&TeamRepo{
  652. OrgID: orgID,
  653. TeamID: teamID,
  654. RepoID: repoID,
  655. })
  656. return err
  657. }
  658. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  659. _, err := e.Delete(&TeamRepo{
  660. TeamID: teamID,
  661. RepoID: repoID,
  662. })
  663. return err
  664. }
  665. // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
  666. func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
  667. teams := make([]*Team, 0, 5)
  668. return teams, x.Where("team.authorize >= ?", mode).
  669. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  670. And("team_repo.org_id = ?", orgID).
  671. And("team_repo.repo_id = ?", repoID).
  672. Find(&teams)
  673. }
  674. // ___________ ____ ___ .__ __
  675. // \__ ___/___ _____ _____ | | \____ |__|/ |_
  676. // | |_/ __ \\__ \ / \| | / \| \ __\
  677. // | |\ ___/ / __ \| Y Y \ | / | \ || |
  678. // |____| \___ >____ /__|_| /______/|___| /__||__|
  679. // \/ \/ \/ \/
  680. // TeamUnit describes all units of a repository
  681. type TeamUnit struct {
  682. ID int64 `xorm:"pk autoincr"`
  683. OrgID int64 `xorm:"INDEX"`
  684. TeamID int64 `xorm:"UNIQUE(s)"`
  685. Type UnitType `xorm:"UNIQUE(s)"`
  686. }
  687. // Unit returns Unit
  688. func (t *TeamUnit) Unit() Unit {
  689. return Units[t.Type]
  690. }
  691. func getUnitsByTeamID(e Engine, teamID int64) (units []*TeamUnit, err error) {
  692. return units, e.Where("team_id = ?", teamID).Find(&units)
  693. }
  694. // UpdateTeamUnits updates a teams's units
  695. func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) {
  696. sess := x.NewSession()
  697. defer sess.Close()
  698. if err = sess.Begin(); err != nil {
  699. return err
  700. }
  701. if _, err = sess.Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil {
  702. return err
  703. }
  704. if _, err = sess.Insert(units); err != nil {
  705. sess.Rollback()
  706. return err
  707. }
  708. return sess.Commit()
  709. }