14 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
15 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
18// GitHubProvider represents an GitHub based Identity Provider
19type GitHubProvider struct {
25// NewGitHubProvider initiates a new GitHubProvider
26func NewGitHubProvider(p *ProviderData) *GitHubProvider {
27 p.ProviderName = "GitHub"
28 if p.LoginURL == nil || p.LoginURL.String() == "" {
29 p.LoginURL = &url.URL{
32 Path: "/login/oauth/authorize",
35 if p.RedeemURL == nil || p.RedeemURL.String() == "" {
36 p.RedeemURL = &url.URL{
39 Path: "/login/oauth/access_token",
42 // ValidationURL is the API Base URL
43 if p.ValidateURL == nil || p.ValidateURL.String() == "" {
44 p.ValidateURL = &url.URL{
46 Host: "api.github.com",
51 p.Scope = "user:email"
53 return &GitHubProvider{ProviderData: p}
56func getGitHubHeader(accessToken string) http.Header {
57 header := make(http.Header)
58 header.Set("Accept", "application/vnd.github.v3+json")
59 header.Set("Authorization", fmt.Sprintf("token %s", accessToken))
63// SetOrgTeam adds GitHub org reading parameters to the OAuth2 scope
64func (p *GitHubProvider) SetOrgTeam(org, team string) {
67 if org != "" || team != "" {
68 p.Scope += " read:org"
72func (p *GitHubProvider) hasOrg(accessToken string) (bool, error) {
73 // https://developer.github.com/v3/orgs/#list-your-organizations
76 Login string `json:"login"`
79 type orgsPage []struct {
80 Login string `json:"login"`
87 "page": {strconv.Itoa(pn)},
91 Scheme: p.ValidateURL.Scheme,
92 Host: p.ValidateURL.Host,
93 Path: path.Join(p.ValidateURL.Path, "/user/orgs"),
94 RawQuery: params.Encode(),
96 req, _ := http.NewRequest("GET", endpoint.String(), nil)
97 req.Header = getGitHubHeader(accessToken)
98 resp, err := http.DefaultClient.Do(req)
103 body, err := ioutil.ReadAll(resp.Body)
108 if resp.StatusCode != 200 {
109 return false, fmt.Errorf(
110 "got %d from %q %s", resp.StatusCode, endpoint.String(), body)
114 if err := json.Unmarshal(body, &op); err != nil {
121 orgs = append(orgs, op...)
125 var presentOrgs []string
126 for _, org := range orgs {
127 if p.Org == org.Login {
128 logger.Printf("Found Github Organization: %q", org.Login)
131 presentOrgs = append(presentOrgs, org.Login)
134 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
138func (p *GitHubProvider) hasOrgAndTeam(accessToken string) (bool, error) {
139 // https://developer.github.com/v3/orgs/teams/#list-user-teams
142 Name string `json:"name"`
143 Slug string `json:"slug"`
145 Login string `json:"login"`
146 } `json:"organization"`
149 type teamsPage []struct {
150 Name string `json:"name"`
151 Slug string `json:"slug"`
153 Login string `json:"login"`
154 } `json:"organization"`
160 params := url.Values{
162 "page": {strconv.Itoa(pn)},
165 endpoint := &url.URL{
166 Scheme: p.ValidateURL.Scheme,
167 Host: p.ValidateURL.Host,
168 Path: path.Join(p.ValidateURL.Path, "/user/teams"),
169 RawQuery: params.Encode(),
172 req, _ := http.NewRequest("GET", endpoint.String(), nil)
173 req.Header = getGitHubHeader(accessToken)
174 resp, err := http.DefaultClient.Do(req)
180 // link header may not be obtained
181 // When paging is not required and all data can be retrieved with a single call
183 // Conditions for obtaining the link header.
184 // 1. When paging is required (Example: When the data size is 100 and the page size is 99 or less)
185 // 2. When it exceeds the paging frame (Example: When there is only 10 records but the second page is called with a page size of 100)
187 // link header at not last page
188 // <https://api.github.com/user/teams?page=1&per_page=100>; rel="prev", <https://api.github.com/user/teams?page=1&per_page=100>; rel="last", <https://api.github.com/user/teams?page=1&per_page=100>; rel="first"
189 // link header at last page (doesn't exist last info)
190 // <https://api.github.com/user/teams?page=3&per_page=10>; rel="prev", <https://api.github.com/user/teams?page=1&per_page=10>; rel="first"
192 link := resp.Header.Get("Link")
193 rep1 := regexp.MustCompile(`(?s).*\<https://api.github.com/user/teams\?page=(.)&per_page=[0-9]+\>; rel="last".*`)
194 i, converr := strconv.Atoi(rep1.ReplaceAllString(link, "$1"))
196 // If the last page cannot be taken from the link in the http header, the last variable remains zero
202 body, err := ioutil.ReadAll(resp.Body)
209 if resp.StatusCode != 200 {
210 return false, fmt.Errorf(
211 "got %d from %q %s", resp.StatusCode, endpoint.String(), body)
215 if err := json.Unmarshal(body, &tp); err != nil {
216 return false, fmt.Errorf("%s unmarshaling %s", err, body)
222 teams = append(teams, tp...)
235 presentOrgs := make(map[string]bool)
236 var presentTeams []string
237 for _, team := range teams {
238 presentOrgs[team.Org.Login] = true
239 if p.Org == team.Org.Login {
241 ts := strings.Split(p.Team, ",")
242 for _, t := range ts {
244 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
248 presentTeams = append(presentTeams, team.Slug)
252 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
255 for org := range presentOrgs {
256 allOrgs = append(allOrgs, org)
258 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
263// GetEmailAddress returns the Account email address
264func (p *GitHubProvider) GetEmailAddress(s *sessions.SessionState) (string, error) {
266 var emails []struct {
267 Email string `json:"email"`
268 Primary bool `json:"primary"`
269 Verified bool `json:"verified"`
272 // if we require an Org or Team, check that first
275 if ok, err := p.hasOrgAndTeam(s.AccessToken); err != nil || !ok {
279 if ok, err := p.hasOrg(s.AccessToken); err != nil || !ok {
285 endpoint := &url.URL{
286 Scheme: p.ValidateURL.Scheme,
287 Host: p.ValidateURL.Host,
288 Path: path.Join(p.ValidateURL.Path, "/user/emails"),
290 req, _ := http.NewRequest("GET", endpoint.String(), nil)
291 req.Header = getGitHubHeader(s.AccessToken)
292 resp, err := http.DefaultClient.Do(req)
296 body, err := ioutil.ReadAll(resp.Body)
302 if resp.StatusCode != 200 {
303 return "", fmt.Errorf("got %d from %q %s",
304 resp.StatusCode, endpoint.String(), body)
307 logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
309 if err := json.Unmarshal(body, &emails); err != nil {
310 return "", fmt.Errorf("%s unmarshaling %s", err, body)
314 for _, email := range emails {
316 returnEmail = email.Email
318 return returnEmail, nil
323 return returnEmail, nil
326// GetUserName returns the Account user name
327func (p *GitHubProvider) GetUserName(s *sessions.SessionState) (string, error) {
329 Login string `json:"login"`
330 Email string `json:"email"`
333 endpoint := &url.URL{
334 Scheme: p.ValidateURL.Scheme,
335 Host: p.ValidateURL.Host,
336 Path: path.Join(p.ValidateURL.Path, "/user"),
339 req, err := http.NewRequest("GET", endpoint.String(), nil)
341 return "", fmt.Errorf("could not create new GET request: %v", err)
344 req.Header = getGitHubHeader(s.AccessToken)
345 resp, err := http.DefaultClient.Do(req)
350 body, err := ioutil.ReadAll(resp.Body)
351 defer resp.Body.Close()
356 if resp.StatusCode != 200 {
357 return "", fmt.Errorf("got %d from %q %s",
358 resp.StatusCode, endpoint.String(), body)
361 logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
363 if err := json.Unmarshal(body, &user); err != nil {
364 return "", fmt.Errorf("%s unmarshaling %s", err, body)
367 return user.Login, nil
370// ValidateSessionState validates the AccessToken
371func (p *GitHubProvider) ValidateSessionState(s *sessions.SessionState) bool {
372 return validateToken(p, s.AccessToken, getGitHubHeader(s.AccessToken))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list