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.

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