github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/jwt/github/client.go (about) 1 package github 2 3 import ( 4 "context" 5 "net/http" 6 7 "github.com/google/go-github/github" 8 ) 9 10 // Client contains the methods that abstract an API 11 type Client interface { 12 CurrentUser(*http.Client) (*github.User, error) 13 Organizations(*http.Client) ([]string, error) 14 Teams(*http.Client) (OrganizationTeams, error) 15 } 16 17 type client struct { 18 baseURL string 19 } 20 21 // NewClient creates a new instance of client 22 func NewClient() Client { 23 return &client{} 24 } 25 26 // OrganizationTeams is a map of organization names and teams 27 type OrganizationTeams map[string][]string 28 29 // CurrentUser retrieves the current authenticated user for an http client 30 func (c *client) CurrentUser(httpClient *http.Client) (*github.User, error) { 31 client := github.NewClient(httpClient) 32 33 currentUser, _, err := client.Users.Get(context.TODO(), "") 34 if err != nil { 35 return nil, err 36 } 37 38 return currentUser, nil 39 } 40 41 // Teams retrieves the teams that the authenticated user belongs 42 func (c *client) Teams(httpClient *http.Client) (OrganizationTeams, error) { 43 client := github.NewClient(httpClient) 44 45 nextPage := 1 46 organizationTeams := OrganizationTeams{} 47 48 for nextPage != 0 { 49 teams, resp, err := client.Teams.ListUserTeams(context.TODO(), &github.ListOptions{Page: nextPage}) 50 if err != nil { 51 return nil, err 52 } 53 54 for _, team := range teams { 55 organizationName := *team.Organization.Login 56 57 if _, found := organizationTeams[organizationName]; !found { 58 organizationTeams[organizationName] = []string{} 59 } 60 61 // We add both forms (slug and name) of team 62 organizationTeams[organizationName] = append(organizationTeams[organizationName], *team.Name) 63 organizationTeams[organizationName] = append(organizationTeams[organizationName], *team.Slug) 64 } 65 66 nextPage = resp.NextPage 67 } 68 69 return organizationTeams, nil 70 } 71 72 // Organizations retrieves the organizations that the authenticated user belongs 73 func (c *client) Organizations(httpClient *http.Client) ([]string, error) { 74 client := github.NewClient(httpClient) 75 76 nextPage := 1 77 organizations := []string{} 78 79 for nextPage != 0 { 80 orgs, resp, err := client.Organizations.List(context.TODO(), "", &github.ListOptions{Page: nextPage}) 81 82 if err != nil { 83 return nil, err 84 } 85 86 for _, org := range orgs { 87 organizations = append(organizations, *org.Login) 88 } 89 90 nextPage = resp.NextPage 91 } 92 93 return organizations, nil 94 }