Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: get user teams with GitHub GraphQL API #2045

Merged
merged 1 commit into from
Feb 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 29 additions & 16 deletions server/events/vcs/github_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,30 +407,43 @@ func (g *GithubClient) MarkdownPullLink(pull models.PullRequest) (string, error)
}

// GetTeamNamesForUser returns the names of the teams or groups that the user belongs to (in the organization the repository belongs to).
// https://developer.github.com/v3/teams/members/#get-team-membership
// https://docs.github.com/en/graphql/reference/objects#organization
func (g *GithubClient) GetTeamNamesForUser(repo models.Repo, user models.User) ([]string, error) {
orgName := repo.Owner
variables := map[string]interface{}{
"orgName": githubv4.String(orgName),
"userLogins": []githubv4.String{githubv4.String(user.Username)},
"teamCursor": (*githubv4.String)(nil),
}
var q struct {
Organization struct {
Teams struct {
Edges []struct {
Node struct {
Name string
}
}
PageInfo struct {
EndCursor githubv4.String
HasNextPage bool
}
} `graphql:"teams(first:100, after: $teamCursor, userLogins: $userLogins)"`
} `graphql:"organization(login: $orgName)"`
}
var teamNames []string
opts := &github.ListOptions{}
org := repo.Owner
ctx := context.Background()
for {
teams, resp, err := g.client.Teams.ListTeams(g.ctx, org, opts)
err := g.v4MutateClient.Query(ctx, &q, variables)
if err != nil {
return nil, errors.Wrap(err, "retrieving GitHub teams")
return nil, err
}
for _, t := range teams {
membership, _, err := g.client.Teams.GetTeamMembershipBySlug(g.ctx, org, *t.Slug, user.Username)
if err != nil {
g.logger.Err("Failed to get team membership from GitHub: %s", err)
} else if membership != nil {
if *membership.State == "active" && (*membership.Role == "member" || *membership.Role == "maintainer") {
teamNames = append(teamNames, t.GetName())
}
}
for _, edge := range q.Organization.Teams.Edges {
teamNames = append(teamNames, edge.Node.Name)
}
if resp.NextPage == 0 {
if !q.Organization.Teams.PageInfo.HasNextPage {
break
}
opts.Page = resp.NextPage
variables["teamCursor"] = githubv4.NewString(q.Organization.Teams.PageInfo.EndCursor)
}
return teamNames, nil
}
Expand Down